从服务器端axios请求发送响应到React/Redux应用 [英] Send response from server side axios request to React/Redux app
问题描述
我对在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请求返回Promise时,我尝试使用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应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!