如何在服务器端呈现的React应用程序中构造多个HTTP请求?

时间:2016-10-20 18:24:40

标签: node.js reactjs redux serverside-rendering

我目前正在使用下面的服务器端渲染逻辑(使用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方法,如果这是一种理想的方法,有人可以告诉我吗?

3 个答案:

答案 0 :(得分:6)

您希望确保请求并行发生,而不是按顺序发生。

我之前通过为每个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

如果有什么不清楚,请告诉我。

答案 1 :(得分:0)

您可以尝试express-batchGraphQL是另一种选择。

答案 2 :(得分:0)

您还可以使用Redux-Sagas使用纯Redux操作来触发多个api调用,并使用纯操作处理所有这些调用。 Introduction to Sagas