【问题标题】:Send response from server side axios request to React/Redux app从服务器端 axios 请求发送响应到 React/Redux 应用程序
【发布时间】:2018-03-11 19:25:49
【问题描述】:

我对在 Node/Express 中创建后端有点陌生,但我正在尝试使用 axios 来发出 HTTP 请求。我已经设置了将发出必要请求的快速路由,并且我通过使用 Postman 知道我正在测试的 GET 请求确实会返回响应。我遇到的困难是如何返回该数据并将其发送到我的 React/Redux 应用程序以供使用。

-服务器端-

//Express Route
app.get('/api/recipes', recipeController.getRecipes)

//Controller Function that makes axios request
const axios = require('axios')
const Promise = require('bluebird')

module.exports = {
  getRecipes(req, res) {
      const url = "https://gw.hellofresh.com/api/recipes/search?country=us&limit=9"
      const token = "IUzI1NiIsInR5c"

      axios
      .get(url, {
        "headers": {"Authorization": "Bearer " + token}
      })
      .then((response) => {
        console.log(response)
      })
      .catch((err) => {
        console.log(err)
      })

  }
}

-客户端-

我调度以下操作并使用我创建的端点进行调用。但是,此时,即使在服务器端我能够得到响应,我也会收到错误状态。当我读到 axios GET 请求返回 Promise 时,我尝试使用 Promises,但无法完全理解如何实现它。

export const getRecipes = () => {
  return (dispatch) => {
    axios
    .get('/api/recipes')
    .then((resp) => {
      console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
  }
}

【问题讨论】:

    标签: node.js reactjs promise axios


    【解决方案1】:

    你需要在路由中调用res.send,将数据发送给客户端:

    module.exports = {
      getRecipes(req, res) {
          const url = "https://gw.hellofresh.com/api/recipes/search?country=us&limit=9"
          const token = "IUzI1NiIsInR5c"
    
          axios
          .get(url, {
            "headers": {"Authorization": "Bearer " + token}
          })
          .then(response => {
            console.log(response)
            res.send(response) // <= send data to the client
          })
          .catch(err => {
            console.log(err)
            res.send({ err }) // <= send error
          })
      }
    }
    

    【讨论】:

    • 谢谢!完全忘记了我的函数中的 res、req 参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2016-07-11
    • 2019-12-02
    • 2021-01-07
    • 2020-05-04
    相关资源
    最近更新 更多