Node.js 路由 - 初识 Express 中的路由

目录

[Node.js 路由 - 初识 Express 中的路由](#Node.js 路由 - 初识 Express 中的路由)

[1. 什么是路由?](#1. 什么是路由?)

[2. 安装 Express](#2. 安装 Express)

[3. 创建 server.js](#3. 创建 server.js)

[4. 运行服务器](#4. 运行服务器)

[5. 测试路由](#5. 测试路由)

[5.1 访问主页](#5.1 访问主页)

[5.2 访问用户路由](#5.2 访问用户路由)

[5.3 发送 POST 请求](#5.3 发送 POST 请求)

[6. 结语](#6. 结语)


1. 什么是路由?

路由(Routing)是指根据不同的 URL 地址,服务器返回不同的内容 。在 Express 中,我们可以使用 app.get()app.post() 等方法定义路由。


2. 安装 Express

bash 复制代码
mkdir express-routing && cd express-routing  # 创建项目目录
npm init -y  # 初始化项目
npm install express  # 安装 Express

3. 创建 server.js

文件名:server.js(JavaScript 代码)

javascript 复制代码
// server.js
const express = require('express'); // 引入 Express
const app = express(); // 创建应用
const port = 3000; // 服务器端口

// 主页路由
app.get('/', (req, res) => {
    res.send('欢迎来到 Express 主页!');
});

// 用户路由(GET 请求)
app.get('/user/:name', (req, res) => {
    const name = req.params.name; // 获取 URL 参数
    res.send(`你好,${name}!`);
});

// 提交数据路由(POST 请求)
app.use(express.json()); // 解析 JSON 请求体
app.post('/submit', (req, res) => {
    const { username, age } = req.body; // 获取请求体数据
    res.json({ message: '数据提交成功', user: { username, age } });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});

4. 运行服务器

执行命令:

bash 复制代码
node server.js

5. 测试路由

5.1 访问主页

浏览器打开 http://localhost:3000/,页面显示:

javascript 复制代码
欢迎来到 Express 主页!
5.2 访问用户路由

浏览器访问 http://localhost:3000/user/Tom,页面显示:

javascript 复制代码
你好,Tom!
5.3 发送 POST 请求

使用 Postman 或 curl 发送请求:

javascript 复制代码
curl -X POST http://localhost:3000/submit -H "Content-Type: application/json" -d '{"username": "Alice", "age": 25}'

服务器返回 JSON 响应:

javascript 复制代码
{
    "message": "数据提交成功",
    "user": {
        "username": "Alice",
        "age": 25
    }
}

6. 结语

本文介绍了 Express 路由 的基本用法,包括 GET 和 POST 请求,以及如何获取 URL 参数和请求体数据。希望这篇教程能帮助你快速上手 Express 路由!🚀

相关推荐
知了清语1 分钟前
使用 codex + GPT 5.4 分析已实现的 数据看板
前端
qq_120840937115 分钟前
Three.js 工程向:相机控制与交互手感调优(OrbitControls)
前端·javascript·orbitcontrols
疯狂的魔鬼15 分钟前
从 5 个 Hooks 到注册表模式:Vue 3 复杂详情页的架构演进与原则沉淀
前端·架构
enoughisenough19 分钟前
WEB网络通信
前端
We་ct37 分钟前
LeetCode 300. 最长递增子序列:两种解法从入门到优化
开发语言·前端·javascript·算法·leetcode·typescript
深海鱼在掘金38 分钟前
Next.js从入门到实战保姆级教程(第一章):导读——建立 Next.js 的认知框架
前端·typescript·next.js
渔舟小调40 分钟前
P17 | 管理台动态路由:后端返回菜单树,前端运行时注入
前端
小徐_23331 小时前
uni-app 组件库 Wot UI 2.0 发布了,我们带来了这些改变!
前端·微信小程序·uni-app
❀͜͡傀儡师1 小时前
Claude Code 官方弃用 npm 安装方式:原因分析与完整迁移指南
前端·npm·node.js·claude code
知识分享小能手1 小时前
ECharts入门学习教程,从入门到精通,ECharts高级功能(6)
前端·学习·echarts