Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Web包开发服务器CORS问题_Reactjs_Cors_Superagent_Webpack Dev Server - Fatal编程技术网

Reactjs Web包开发服务器CORS问题

Reactjs Web包开发服务器CORS问题,reactjs,cors,superagent,webpack-dev-server,Reactjs,Cors,Superagent,Webpack Dev Server,我正在使用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-Ori

我正在使用
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中,我使用
request
from
superagent
生成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

有没有解决这个问题的建议?非常感谢您从
localhost:5050
运行JavaScript,但是您的API服务器是
localhost:8000
。这违反了同源策略,因此浏览器不允许它


您可以修改您的API服务器,以便,或者按照“与现有服务器结合”下的操作,将资产服务与webpack dev server和您自己的API服务器结合起来。

对于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已解决

另一种解决方法是直接将所需的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"
  }
}
文档链接

    • 也有同样的问题,但我的api使用的是https协议(.)。必须使用https启动服务器并使用


      有两种解决方案。第一个是在客户端设置代理,第二个是在服务器上设置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);
                  }
                },
              },
            },
          },
          
        };
      };
      

      你在哪里找到这个的链接?它在网页文档中:添加这个对我不起作用,没有任何改变。但我仍然收到缺少access control allow headers标头的错误。通常只要将“access control allow Origin”放在那里就足够了。如果您还通过某种重定向(代理、ssh重定向等)使用浏览器,请使用devServer选项
      sockPort:'location'
      ,这样套接字端口将使用与位置端口相同的端口,这通常就足够了。第二个链接现在断开了。这是官方文件。这对我不起作用。仍出现异常,表示CORS策略已阻止从源“”获取“”的访问:“访问控制允许源”标头具有值“”。我有意在后端添加了“”。只是为了验证代理是否在我的前端工作,此设置不会限制我的api调用。我认为这是一个有点不同的问题,但显然,仅设置
      端口:8080对我来说就足够了。我只是想启用“热重新加载”(在使用Vue时)。无论如何谢谢你!我喜欢这个解决方案,因为据我所知,这个设置最接近典型的生产设置,例如,一个合适的NGINX配置将类似地将前端+后端统一在同一个源下。这正是我所寻找的!谢谢
      
      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);
                  }
                },
              },
            },
          },
          
        };
      };