问题描述
我对在 Node/Express 中创建后端有点陌生,但我正在尝试使用 axios 发出 HTTP 请求.我已经设置了将发出必要请求的快速路由,并且我从使用 Postman 得知我正在测试的 GET 请求确实返回了响应.我遇到的问题是如何返回该数据并将其发送到我的 React/Redux 应用程序以使用.
I'm a little new to creating a backend in Node/Express, but I am trying use axios to make HTTP requests. I've set up express routes that will make the necessary request and I know from using Postman that GET request I'm testing does return a response. Where I'm stuck is how to return that data and send it to my React/Redux app to use.
-服务器端-
//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 请求返回承诺时,我尝试使用 Promises,但无法理解如何实现它.
I dispatch the following action and make a call using the endpoint I created. However, at this point, I'd get an error status even though on the server side I was able to get a response. I tried playing around using Promises as I read that axios GET requests returns promises, but couldn't wrap my head around on how to implement it.
export const getRecipes = () => {
return (dispatch) => {
axios
.get('/api/recipes')
.then((resp) => {
console.log(resp)
})
.catch((err) => {
console.log(err)
})
}
}
推荐答案
需要在路由中调用res.send
,将数据发送给客户端:
You need to call res.send
in the route, to send the data to the client:
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
})
}
}
这篇关于将服务器端 axios 请求的响应发送到 React/Redux 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!