Express 中 get 参数获取

1. 使用 req.query 获取 URL 查询字符串参数

在 GET 请求中,参数通常以查询字符串的形式附加在 URL 后面,格式为 ?参数名1=值1&参数名2=值2 。Express 里可通过 req.query 对象获取这些参数。

const express = require("express");
const app = express();
// 定义处理 GET 请求的路由
app.get("/search", (req, res) => {
  // 获取查询字符串中的参数
  const keyword = req.query.keyword;
  const category = req.query.category;
  // 根据参数进行相应处理
  if (keyword && category) {
    res.send(`You searched for ${keyword} in the ${category} category.`);
  } else if (keyword) {
    res.send(`You searched for ${keyword}.`);
  } else {
    res.send("No search keyword provided.");
  }
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

2. 获取路由参数

除了查询字符串参数,还可通过路由参数传递数据。路由参数是在路由路径中定义的动态部分,用冒号 : 标识。

const express = require("express");
const app = express();
// 定义包含路由参数的路由
app.get("/products/:productId", (req, res) => {
  // 获取路由参数
  const productId = req.params.productId;
  res.send(`You requested product with ID: ${productId}`);
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

3. 处理多个同名参数

如果查询字符串中存在多个同名参数,req.query 会将它们的值存储在一个数组中。

const express = require("express");
const app = express();
app.get("/tags", (req, res) => {
  const tags = req.query.tag;
  if (Array.isArray(tags)) {
    res.send(`You provided multiple tags: ${tags.join(", ")}`);
  } else if (tags) {
    res.send(`You provided a single tag: ${tags}`);
  } else {
    res.send("No tags provided.");
  }
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yqcoder

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值