2016-08-03 47 views
1

我有一个使用React Router和Redux作为其状态管理器的React App。该应用程序的服务器端使用Express和Node。如何克服Redux React Express和Node的CORS问题?

我正在对外部服务进行API调用。我无法在外部服务上启用CORS。因此,我需要使用我的应用服务器端来调用外部服务,以从等式中删除浏览器,并消除任何CORS错误。

我能够成功从服务器端的服务获取数据。我想知道是否有可能通过某种中间件(查找示例/资源)在客户端和服务器之间共享Redux存储。

目标:

1)在客户端

2)有一个事件调用服务器端路线外部API(不知道如何做到这一点)

处理click事件

3)然后,服务器处理此路由,使得该请求,并且向客户端发送所述响应(通过共享反应商店 - 不知道这是可能的)

4)商店获得新的状态,一个然后发送到客户端组件和UI更新

是否有任何这样的示例/教程?不寻找最初的服务器渲染页面,但指导如何通常执行上述4个步骤。

+0

您使用哪个库来进行API请求?的SuperAgent /取? – Deadfish

+0

检出我目前正在构建的这个例子,已经支持universal react/redux应用程序:https://github.com/alexnm/react-seed。另外如果你想检查一个更复杂的例子,我建议MERN启动器:https://github.com/Hashnode/mern-starter –

回答

2

感谢您的建议。

事实证明,我在考虑解决方案时非常seve。。我真正需要的是能够从客户端事件(加载组件)启动服务器端功能(从外部API获取资源)。如何提交表单,具有启动服务器端功能的动作。

在我的组件:

componentDidMount() { 
    const product_api_results = productApi.getProductItems() 
    console.log('product_api_results in CART Component: ', product_api_results) 
    /* now I have results and can put it in the Redux Store via action to reducer for other components to work with on client */ 
    } 

的productAPI.getProductItems(),该组件调用:

export function getProductItems() { 
    return axios.get('/api/get-products') // triggers a server side route 
    .then(function (response) { 
     console.log('client side response: ', response) 
     return response 
    }) 
} 

在快递server.js文件时,服务器会看到这个URL,然后拿到正确的数据。 shopify.get()来自shopify-node-api模块:

app.get('/api/get-products', function (req, res) { // '/api/get-products' called from client 
    shopify.get('/admin/products.json', function (err, data, headers) { 
    res.send(data) 
    }) 
})