【发布时间】: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