Skip to content

参数获取

query 参数

express 框架封装了一些 API 来方便获取请求报文中的数据。

js
app.get("/hot", (request, response) => {
  // 获取查询字符串
  console.log(request.query);
  // 获取指定请求头
  console.log(request.get("host"));
  response.send("<h1>hello</h1>");
});

params 参数

params 参数又称路由参数,指的是 URL 路径中的参数。

js
let goods = {
  "00001": { title: "联想电脑Y9000P", price: 10899 },
  "00002": { title: "海尔冰箱TK3000", price: 4999 },
};

// id相当于占位符
app.get("/:id.html", (request, response) => {
  // 获取路由参数
  console.log(request.params.id);
  // 根据不同的id返回不同的内容
  const { id } = request.params;
  response.send(`
    <h1>商品名称:${goods[id].title}</h1>
    <h2>商品价格:${goods[id].price}</h2>
  `);
});

请求体参数

请求体参数

express 中获取请求体参数,需要借助中间件来完成,下文中会详细讲解