【问题标题】:How to acess axios params in nodejs get request如何在nodejs获取请求中访问axios参数
【发布时间】:2021-02-26 17:28:20
【问题描述】:

我正在使用 axios 向 API 发送 get 请求,但无法访问该请求中传递的参数。

这是我的代码: API 请求

 axios.get('http://localhost:4000/students',{
          params: {
            category:"indoor"
          }
        })

请求处理

router.route('/').get((req, res) => {
  console.log(req.params.category);
  studentSchema.find({category:req.params.category},(error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})

在没有给定参数的情况下,路由工作正常。

console.log(req.params.category);输出未定义。

希望你有问题...

【问题讨论】:

标签: node.js api mongoose axios


【解决方案1】:

Axios 中的params 是成为querystring 的URL 参数。

Express 的请求对象中的params 是路由参数。例如:当我定义一个 URL 如/students/:id 时,req.params for GET /students/value 将是{id: "value"}

您在 Express 处理程序中寻找的是 req.query [docs]。

【讨论】:

    【解决方案2】:

    我相信你所做的与 Axios 无关, 要获取查询参数,在您的代码的服务器端,您需要使用请求的属性query,如下所示:

    let category = req.query["category"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 2021-12-29
      • 2022-01-03
      • 2021-05-11
      • 2021-03-27
      • 2017-11-18
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多