当前位置: 首页 > news >正文

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}`);
});

相关文章:

  • 51 单片机中断控制寄存器 TCON
  • Python爬虫:爬虫基础知识
  • 解决电脑问题(2)——主板问题
  • MySQL面试篇——性能优化
  • 微分方程家族:常微分方程(ODE)、偏微分方程(PDE)和随机微分方程(SDE)
  • Redis-主从架构
  • SQL SELECT DISTINCT 语句
  • JavaSE-5 类和对象
  • 51单片机之蓝牙模块的使用
  • 图神经网络的健壮性(五)
  • STL map 的 lower_bound(x)、upper_bound(x) 等常用函数
  • 2025年渗透测试面试题总结-长某亭科技-安全服务工程师(一面)(题目+回答)
  • Python卷积神经网络(CNN)来识别和计数不同类型的工业零件
  • 基于ssm的物资进销存(全套)
  • .net 与 Pythonnet库的使用心得
  • idea 创建springboot 项目,连接数据库,后台接口实现
  • ajax之生成一个ajax的demo示例
  • QSplitter.setStretchFactor无效
  • 分析TCP三次握手与四次挥手
  • 前沿科技展望未来发展趋势
  • 小地方网站建设公司/专业代写文案的公司
  • php盗版视频网站怎么做的/seo网站排名优化案例
  • 上海优化网站/技能培训班有哪些课程
  • 公司网站用什么开发/今日头条热搜榜
  • 从凡客诚品的案例分析b2c电子商务网站该怎样建设网络品牌/怎么做好网站方式推广
  • 网站描述作用/seo排名优化推荐