不敢相信我必须问这个,但是我如何从 Express 中的 get 请求中获取路由参数?



,所以我坐在客户端上定义为/article/:id的路由上,然后查询服务器API:

const res = await axios.get(url + '/api/article')

(不用担心url,只是为了获得绝对路径。(

然后我有我的路线:

router.get('/article', function(req, res) {
  //I want to find the id from the params
  //Trying fucking everything
  console.log("host", req.get('host')) // 'localhost:3000'
  console.log("url", req.url) // '/article'
  console.log("query", req.query) // '{}'
 })

显然,这在Express/Axios世界中是疯狂的东西,因为我已经花了整整一天的时间试图找出如何做到这一点,但是没有关于此主题的信息。

我如何完成这个愚蠢的简单任务?

您的请求是

const res = await axios.get(url + '/api/article')

您不发送ID。如果要进行查询,则应

const res = await axios.get(url + '/api/article?id=theId')

并使用req.query.id或者您必须将路线更改为

router.get('/article/:id', ....

致电const res = await axios.get(url + '/api/article/theId')

并使用req.params.id

router.get('/article/:id', function(req, res) {
    //I want to find the id from the params
    console.log(req.params.id)
})

从这里获取:https://expressjs.com/en/guide/routing.html

最新更新