簡體   English   中英

從服務器端axios請求發送響應到React / Redux應用

[英]Send response from server side axios request to React/Redux app

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

您需要在路由中調用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
      })
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM