Webpack开发服务器,Cors出现问题,因为引荐来源网址在本地主机上有差异端口

问题描述

我有时间恶魔试图解决这个问题。我对以下各项进行了修改

注意:在本地,我正在使用webpack开发服务器。

我的本​​地主机是端口8081,并且遇到了一个期望引用为“本地主机”的后端。我相信起源会加剧这一点。我的错误是:

Access to fetch at 'http://localhost/api/clients/carts' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

我已经如下修改了Webpack开发服务器:

  devServer: {
    port: 8081,contentBase: './src',historyApiFallback: true,hot: true,headers: {
      // WITH and WITHOUT THIS
      "Access-Control-Allow-Origin": "*"
    },proxy: {
      secure: false,changeOrigin: true,bypass: (req,res) => {
        if (req.headers && req.headers.referer) {
          req.headers.referer = 'http://localhost';
        }
      },},

部分是我传递给fetch调用内容

  const requestOptions: RequestOptions = {
    credentials: 'include',method,headers: {
      Accept: 'application/json','Content-Type': 'application/json',};

即使我尝试覆盖引荐来源,我仍然可以得到它:

Referer: http://localhost:8081/products

注:看来,我有在端口80上运行的Nginx。因此,我需要webpack仍然像来自本地主机的行为一样。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)