创建 React App 添加 CORS 标头

ber*_*tet 4 javascript node.js cors reactjs create-react-app

我试图找出将“Access-Control-Allow-Origin”标头添加到我的 create-react-app dev Server 配置的位置。

到目前为止,我将它添加到config/webpackDevServer.config.js没有太多运气。

知道我可以在哪里添加它吗?

谢谢!

Qua*_*ion 5

这是一个基于@tlfu 对使用react-app-rewired. 在这种情况下,您需要定义一个config-overrides.js包含以下内容的根级文件:

module.exports = {
  // Extend/override the dev server configuration used by CRA
  // See: https://github.com/timarney/react-app-rewired#extended-configuration-options
  devServer: function(configFunction) {
    return function(proxy, allowedHost) {
      // Create the default config by calling configFunction with the proxy/allowedHost parameters
      // Default config: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpackDevServer.config.js
      const config = configFunction(proxy, allowedHost);

      // Set loose allow origin header to prevent CORS issues
      config.headers = {'Access-Control-Allow-Origin': '*'}

      return config;
    };
  },
};

Run Code Online (Sandbox Code Playgroud)


nik*_*krb 0

如果我搞错了,我很抱歉,但从你的问题来看,我猜测你正在使用带有 React 前端的后端 api。据我所知,您不需要 cors,只需将代理添加到您的客户端/前端 package.json: "proxy": "http://localhost:5000/" Dan 确实说这仅适用于简单情况,但我希望它有所帮助