Express 路由使用、请求报文参数获取、路由参数提取

Express 路由使用、请求报文参数获取、路由参数提取


🛣️ 一、Express 路由基本用法

const express = require('express');
const app = express();

// 基本 GET 路由
app.get('/', (req, res) => {
  res.send('Hello GET!');
});

// POST 路由
app.post('/submit', (req, res) => {
  res.send('Hello POST!');
});

// 其他方法
app.put('/update', (req, res) => {
  res.send('PUT 更新');
});

app.delete('/delete', (req, res) => {
  res.send('DELETE 删除');
});

📦 二、获取请求报文参数

1. Query 参数(URL 上的 ?name=xxx&age=xx

app.get('/search', (req, res) => {
  const { name, age } = req.query;
  res.send(`查询名字:${name},年龄:${age}`);
});

访问:http://localhost:3000/search?name=Tom&age=18
结果:查询名字:Tom,年龄:18


2. Body 参数(常用于 POST、PUT)

要先配置中间件:

app.use(express.json()); // 解析 JSON 格式
app.use(express.urlencoded({ extended: true })); // 解析表单(x-www-form-urlencoded)
app.post('/submit', (req, res) => {
  const { username, password } = req.body;
  res.send(`用户名:${username},密码:${password}`);
});

📌 三、提取路由参数(Path Param)

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`用户 ID 是:${userId}`);
});

访问:http://localhost:3000/user/123
结果:用户 ID 是:123

你也可以定义多个参数:

app.get('/user/:userId/book/:bookId', (req, res) => {
  const { userId, bookId } = req.params;
  res.send(`用户 ${userId} 查看书籍 ${bookId}`);
});

📚 四、整合小示例

const express = require('express');
const app = express();
const port = 3000;

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// GET + query
app.get('/search', (req, res) => {
  res.send(req.query);
});

// POST + body
app.post('/submit', (req, res) => {
  res.send(req.body);
});

// 路由参数
app.get('/user/:id', (req, res) => {
  res.send(req.params);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻小胖

如果觉得不错就给点赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值