【问题标题】:Express: req.params returning undefined快递:req.params 返回 undefined
【发布时间】:2019-05-24 17:59:32
【问题描述】:

在使用 url 参数的服务器端获得了简单的 get 方法,以及对该 url 的客户端请求(反应),但问题是服务器返回未定义的参数。这是代码:

服务器(index.js):

router.use('/api/info/:name/:id', require('./info'))`

info.js:

router.get('/', async (req, res) => {
try {
   const name = req.params.name;
   const id = req.params.id;
   console.log('name ' + name +'  id  ' + id)

    return res.status(200).send({
       id: id,
       name: name
    })
} catch (err) {
    return res.status(500).send({
      message: err.message
    })
  }
})

和客户端(ReactJS):

componentDidMount(){
 const { match: { params } } = this.props;
    axios.get(`/api/recipe/${params.name}/${params.id}`)              
      .then(res => res.data)
      .then(data =>{
         console.log(data)
    })      
}

正如我所说,此代码在服务器端返回未定义的名称和 ID,但客户端工作(我记录它并且它是有效的)。在控制台中它也给了我这个错误(DevTools 的控制台)

未捕获(承诺中)错误:请求失败,状态码为 500

怎么了?谢谢!

【问题讨论】:

    标签: javascript node.js regex reactjs express


    【解决方案1】:

    您在index.js 中定义的路由是/api/info/title/:id,但您正在对/api/recipe/${params.name}/${params.id} 进行API 调用。您的路线不匹配,并且您没有将 :name 定义为参数。

    除非这是您的拼写错误,否则更改您的 router.use 代码以匹配您的 API 调用应该可以:

    router.use('/api/recipe/:name/:id', require('./info'));
    

    【讨论】:

    • 在你的 React 代码中,你的 .get 代码是 api/recipe,而不是你在服务器中定义的 api/info。你打错了终点。
    • 对不起,我希望我可以删除我的帖子。问题是我修改了我的 url 参数名称以在此处发布,我忘记将配方修改为 info
    【解决方案2】:

    你没有告诉 Express 需要参数(参见“参数”部分 here),你需要这样的东西:

    router.get('/:name/:id', async (req, res) => { ... })
    

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 2017-05-20
      • 2017-11-02
      • 2014-10-24
      • 2020-03-16
      • 2022-11-14
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多