【问题标题】:webpack dev server CORS issuewebpack 开发服务器 CORS 问题
【发布时间】:2015-10-14 15:56:03
【问题描述】:

我正在使用webpack-dev-server v1.10.1 来提升我的 Redux 项目,我有以下选项:

contentBase: `http://${config.HOST}:${config.PORT}`,
quiet: false,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: configWebpack.output.publicPath,
headers: {"Access-Control-Allow-Origin": "*"},
stats: {colors: true}

在 JS 中,我使用来自 superagentrequest 来生成 HTTP GET 调用

request
          .get(config.APIHost + apiUrl)
          .set('Accept', 'application/json')
          .withCredentials()
          .end(function (err, res) {
                if (!err && res.body) {
                    disptach(() => {
                        return {
                            type: actionType || GET_DATA,
                            payload: {
                                response: res.body
                            }
                        }
                    });
                }
          });

但我收到了 CORS 错误:

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access

有解决此问题的建议吗?非常感谢

【问题讨论】:

    标签: reactjs webpack cors webpack-dev-server superagent


    【解决方案1】:

    另一种解决方法是将所需的 CORS 标头直接添加到开发服务器:

    devServer: {
      ...
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
        "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
      }
    }
    

    文档链接

    【讨论】:

    • 任何链接到您在哪里找到的?
    • 添加这个对我不起作用,没有任何改变。我仍然收到缺少 access-control-allow-headers 标头的错误。
    • 通常只要把“Access-Control-Allow-Origin”放在那里就足够了。
    • 如果你也通过一些重定向(proxy, ssh redirect, ...)使用浏览器,使用devServer选项sockPort: 'location',所以socket端口会和location端口一样使用,通常是够了。
    【解决方案2】:

    使用 webpack-dev-server 1.15.X 你可以在你的配置文件中使用这个配置:

    devServer: {
       contentBase: DIST_FOLDER,
       port: 8888,
       // Send API requests on localhost to API server get around CORS.
       proxy: {
          '/api': {
             target: {
                host: "0.0.0.0",
                protocol: 'http:',
                port: 8080
             },
             pathRewrite: {
                '^/api': ''
             }
          }
       }
    },
    

    通过此示例,您将所有呼叫从 http://0.0.0.0:8888/api/* 重定向到 http://0.0.0.0:8080/* 并解决了 CORS

    【讨论】:

    • 这对我不起作用。仍然收到异常说 Access to fetch at 'localhost:8080/api/auth' from origin 'localhost:9000' 已被 CORS 策略阻止:'Access-Control-Allow-Origin' 标头具有值'localhost:7000'。我故意在后端添加了“localhost:7000”。只是为了验证代理是否在我的前端工作,此设置不会限制我的 api 调用。
    • 我相信这是一个有点不同的问题,但显然只设置port: 8080 对我来说就足够了。我只是想启用“热重载”(在使用 Vue 时)。还是谢谢你!
    • 我喜欢这个解决方案,因为据我所知,这个设置最接近典型的生产设置,例如适当的 NGINX 配置将类似地将前端 + 后端统一在同一来源下。
    【解决方案3】:

    您正在从 localhost:5050 运行 JavaScript,但您的 API 服务器是 localhost:8000。这违反了同源策略,因此浏览器不允许这样做。

    您可以修改您的 API 服务器以使用 CORS is enabled,或者按照“与现有服务器结合”下的 the instructions on the webpack-dev-server page 将资产服务与 webpack-dev-server 和您自己的 API 服务器结合起来。

    【讨论】:

    【解决方案4】:

    遇到了同样的问题,但我的 api 使用的是 https 协议 (https://api....)。必须使用 https 启动服务器并使用 https://localhost:8080

    devServer: {
        https: true,
        headers: {
            "Access-Control-Allow-Origin": "*",
        },
        // ....
    }
    

    【讨论】:

    • 这正是我想要的!谢谢!!
    【解决方案5】:

    有两种解决方案。第一个是在客户端设置代理,第二个是在服务器上设置 CORS。 CORS 是服务器问题,服务器不允许来自不同来源的访问。即使使用不同的端口也被认为是不同的来源

    第一个解决方案

    在您的后端代码中,您必须设置此标头:这是 express node.js 中的示例

    app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
      );
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      next();
    });
    

    第二种解决方案:

    在 webpack config.js 中,如果你想传递任何变量,我们导出

    module.exports=function(env){
    return {}} 
    

    而不是

    module.exports={}
    

    我们通过脚本注入这个env

    "dev-server": "webpack-dev-server --env.api='https://jsonplaceholder.typicode.com/users'",
    

    现在 webpack 可以访问这个环境了。在 webpack.config.js 中

    module.exports = function ({
      api = "https://jsonplaceholder.typicode.com/users",
    }) {
      return {
        entry: { main: "./src/index.js" },
        output: {
          path: path.resolve(__dirname, "public"),
          filename: "[name]-bundle.js",
          publicPath: "/",
        },
        mode: "development",
        module: {
          rules: [
            {
              loader: "babel-loader",
              test: /\.js$/,
              exclude: [/node_modules/],
            },
            
            {
              // Load other files, images etc
              test: /\.(png|j?g|gif|ico)?$/,
              use: "url-loader",
            },
            {
              test: /\.s?css$/,
              use: ["style-loader", "css-loader", "sass-loader"],
            },
          ],
        },
        //Some JavaScript bundlers may wrap the application code with eval statements in development.
        //If you use Webpack, using the cheap-module-source-map setting in development to avoid this problem
        devtool: "cheap-module-eval-source-map",
        devServer: {
          contentBase: path.join(__dirname, "public"),
          historyApiFallback: true,
          proxy: {
            "/api": {
              changeOrigin: true,
              cookieDomainRewrite: "localhost",
              target: api,
              onProxyReq: (proxyReq) => {
                if (proxyReq.getHeader("origin")) {
                  proxyReq.setHeader("origin", api);
                }
              },
            },
          },
        },
        
      };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 2020-03-19
      • 2016-12-17
      • 2022-11-04
      • 2021-10-31
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      相关资源
      最近更新 更多