【问题标题】:Passing response data (res.json) from an express route to a react axios post method将快速路由中的响应数据 (res.json) 传递给 react axios post 方法
【发布时间】:2018-07-25 06:45:24
【问题描述】:
axios({
  url: 'myurl.com',
  method: 'post',
  data:data,})
    .then(function(response) {
      this.setState({auth:response}); //this is where I want to send express response to
    }).catch(function(err) {
      console.log(err);
    })

这是我的 axios 调用,它将用户输入传递给我的快速路由。

app.post('myurl.com', function(req,res) {
  const user = req.body.data
  const pass = req.body.otherData
  const token = await db.call(req,res,user,pass)
  \\ res.json = token ?
})

这是使用用户输入查询数据库的快速路由。这是我想将 db 查询的结果设置为变量并将其作为响应发送回 axios 调用的地方。我正在尝试做的事情是否可能?

【问题讨论】:

    标签: reactjs express axios


    【解决方案1】:

    你很亲密

    app.post('myurl.com', function(req,res) {
      const user = req.body.data
      const pass = req.body.otherData
      const token = await db.call(req,res,user,pass)
      res.status(200).send({token})
    })
    

    【讨论】:

      【解决方案2】:

      await 语句应该在async function 内。

      app.post('myurl.com', async function(req,res) { //add async to function
      
      //put await statement inside try/catch
        try{
      
            const token = await db.call(req,res,user,pass)
            res.json({token}) //use json function from resp to send json response
      
        }catch(error){
            res.json({error})
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2017-06-07
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多