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

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

http://www.kler.cn/a/583495.html

相关文章:

  • VSCode 配置优化
  • 密码学笔记
  • PyTorch 和 Python关系
  • Unity 封装一个依赖于MonoBehaviour的计时器(上) 基本功能
  • 图片OCR多区域识别并重命名图片文件,基于Python和阿里云的实现方案
  • C#中常量详解
  • 理解C语言中的extern关键字
  • qt之No executable specified
  • QT系列教程(21) 自定义模型的拖动实现
  • ARM嵌入式低功耗高安全:工业瘦客户机的智慧城市解决方案
  • 6. MySQL 索引的数据结构(详细说明)
  • 机器人领域专业名词汇总
  • SpringBoot快速接入DeepSeek-R1大模型(JDK1.8)
  • 机器人交互系统 部署构建
  • Flutter 学习之旅 之 flutter 在设备上进行 全面屏 设置/隐藏状态栏/隐藏导航栏 设置
  • Leetcode做题记录----2
  • 深入理解 C# 反射:基础原理与实际应用
  • 第14章 kali linux(网络安全防御实战--蓝军武器库)
  • c++ 嵌入汇编的方式实现int型自增
  • QT创建项目(项目模板、构建系统、选择类、构建套件)