如何克服 Redux React Express 和 Node 的 CORS 问题?

How To Overcome CORS issues with Redux React Express and Node?

我有一个 React 应用程序,它使用 React Router 和 Redux 作为其状态管理器。应用程序的服务器端使用 Express 和 Node。

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

我能够成功地从服务器端的服务中获取我的数据。我想知道是否可以通过某种中间件(寻找 examples/resources)在客户端和服务器之间共享 Redux 存储。

目标:

1) 在客户端处理点击事件

2) 让该事件调用到外部的服务器端路由 api(不知道该怎么做)

3) 然后服务器处理这个路由,发出请求,并将响应发送给客户端(通过共享的反应存储 - 不确定这是否可能)

4) store 获取新状态,然后发送给客户端组件,UI 更新

这个有examples/tutorials吗?不是在寻找初始服务器呈现的页面,而是在寻找通常如何实施上述 4 个步骤的指南。

感谢您的建议。

事实证明,我严重过度思考了解决方案。我真正需要的是能够从客户端事件(加载组件)启动服务器端功能(从外部 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
    })
}

在 Express 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)
  })
})