我目前正在使用下面的服务器端渲染逻辑(使用 reactjs + nodejs +redux)来第一次同步获取数据并将其设置为存储中的初始状态。
fetchInitialData.js
export function fetchInitialData(q,callback){
const url='http://....'
axios.get(url)
.then((response)=>{
callback((response.data));
}).catch((error)=> {
console.log(error)
})
}
我使用回调异步获取数据并加载输出以存储页面第一次加载。
handleRender(req, res){
fetchInitialData(q,apiResult => {
const data=apiResult;
const results ={data,fetched:true,fetching:false,queryValue:q}
const store = configureStore(results, reduxRouterMiddleware);
....
const html = renderToString(component);
res.status(200);
res.send(html);
})
}
我需要在初始页面加载时进行 4 到 5 个 API 调用,因此考虑检查是否有一种简单的方法可以在页面加载时进行多次调用。
我是否需要链接 API 调用并手动合并来自不同 API 调用的响应并将其发回以加载初始状态?
更新 1: 我正在考虑使用 axios.all 方法,有人可以告诉我这是否是理想的方法吗?
最佳答案
您希望确保请求并行发生,而不是按顺序发生。
我之前通过为每个 API 调用创建一个 Promise 解决了这个问题,并使用 axios.all()
等待所有调用。下面的代码是
基本上是伪代码,以后我可以深入研究更好的实现。
handleRender(req, res){
fetchInitialData()
.then(initialResponse => {
return axios.all(
buildFirstCallResponse(),
buildSecondCallResponse(),
buildThirdCallResponse()
)
})
.then(allResponses => res.send(renderToString(component)))
}
buildFirstCallResponse() {
return axios.get('https://jsonplaceholder.typicode.com/posts/1')
.catch(err => console.error('Something went wrong in the first call', err))
.then(response => response.json())
}
注意如何将所有响应捆绑到一个数组中。
Redux 文档稍微介绍了服务器端渲染,但您可能已经看到了。 redux.js.org/docs/recipes/ServerRendering
同时查看 Promise 文档以了解 .all()
的确切功能。 developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
如果有任何不清楚的地方,请告诉我。
关于node.js - 如何在服务器端呈现的 React 应用程序中构造多个 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40161840/