从服务器端axios请求发送响应到React / Redux应用程序

时间:2017-09-29 20:25:32

标签: node.js reactjs promise axios

我在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)
      })

  }
}

-Client Side -

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

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

1 个答案:

答案 0 :(得分:3)

您需要在路线中呼叫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
      })
  }
}
相关问题