表达:req.params、req.query 和 req.body

2025-06-05

表达:req.params、req.query 和 req.body

req.body、req.query 和 req.params 是 Express 请求对象的一部分。
客户端使用它们向服务器发送数据。
本文概述了它们的区别,并提供了如何使用它们的示例。

1. 请求主体

通常用于 POST/PUT 请求。
当你需要向服务器发送敏感数据(例如表单数据)或超长 JSON 数据时,请使用它。

如何在请求体中发送数据

  • 使用 curl
  curl -d '{"key1":"value1", "key2":"value2"}' -H "ContentType: application/json" -X POST http://localhost:3000/giraffe
Enter fullscreen mode Exit fullscreen mode
  • 使用 axios
  axios.post('/giraffe', {
    key1: 'value1',
    key2: 'value2'
  })
  .then(response => {
    ...
  })
  .catch(error => {
    ...
  })
Enter fullscreen mode Exit fullscreen mode

如何从请求主体中获取数据

  app.get('/giraffe', (req, res) => {
   console.log(req.body.key1) //value1
   console.log(req.body.key2) //value2
  })
Enter fullscreen mode Exit fullscreen mode

记住使用 express.json() 中间件来解析请求主体,否则你会得到一个错误

app.use(express.json())
Enter fullscreen mode Exit fullscreen mode

2. req.params

这些是附加到 URL 的属性,即命名路由参数。在编写路由时,需要在参数名称前加上冒号 (:)

例如,

  app.get('/giraffe/:number', (req, res) => {
   console.log(req.params.number)
  })
Enter fullscreen mode Exit fullscreen mode

要从客户端发送参数,只需将其名称替换为值

  GET  http://localhost:3000/giraffe/1
Enter fullscreen mode Exit fullscreen mode

3. req.查询

req.query 主要用于搜索、排序、过滤、分页等。
比如说,你想查询一个 API,但只想获取第 10 页的数据,你通常会使用 req.query。
它的写法是key=value。

  GET  http://localhost:3000/animals?page=10
Enter fullscreen mode Exit fullscreen mode

在您的快速服务器中访问它也非常简单;

  app.get('/animals', ()=>{
   console.log(req.query.page) // 10
  })
Enter fullscreen mode Exit fullscreen mode

我希望您觉得这有帮助。

感谢阅读🥰。

封面照片由Adi GoldsteinUnsplash上拍摄

文章来源:https://dev.to/gathoni/express-req-params-req-query-and-req-body-4lpc
PREV
Vue 3 即将到来!
NEXT
如何使用私有 git repo 作为 npm 模块设置 repo 设置你的项目使用包将 repo 安装为模块更新结论