webpack 开发服务器 CORS 问题 [英] webpack dev server CORS issue

查看:44
本文介绍了webpack 开发服务器 CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using webpack-dev-server v1.10.1 to boost up my Redux project and I have the options below:

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 调用

In the JS, I am using request from superagent to generate a HTTP GET call

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 错误:

But I got the CORS error:

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

有什么建议可以解决这个问题吗?非常感谢

Any suggestion to resolve this? Thanks a lot

推荐答案

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

Another way to work around it is to directly add the required CORS headers to the dev server:

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"
  }
}

文档链接

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆