webpack dev服务器CORS问题

时间:2015-07-24 05:16:46

标签: reactjs cors superagent webpack-dev-server

我正在使用public static void SetEntityProperty(object entity, DevExpress.Web.ASPxFormLayout formLayoutControl) { if (formLayoutControl != null) { Type type = entity.GetType(); System.Reflection.PropertyInfo[] properties = type.GetProperties(); System.Data.DataTable dt = new System.Data.DataTable(); foreach (System.Reflection.PropertyInfo pi in properties) { var layoutItem = formLayoutControl.FindItemByFieldName(pi.Name); if (layoutItem != null && layoutItem.CssClass == "ro-item") continue; var control = formLayoutControl.FindNestedControlByFieldName(pi.Name); if (control != null && control is DevExpress.Web.ASPxEdit) { var targetType = Data.IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType; try { if ((control as DevExpress.Web.ASPxEdit).Value != null) { //here (control as DevExpress.Web.ASPxEdit).Value = "19/05/2015" and control is a read only text box var value = Convert.ChangeType((control as DevExpress.Web.ASPxEdit).Value, targetType); if (value != null && value is System.String) { value = value.ToString().Trim(); (control as DevExpress.Web.ASPxEdit).Value = value; } pi.SetValue(entity, value, null); } else { pi.SetValue(entity, null, null); } } catch (Exception ex) { pi.SetValue(entity, value, null); } } else throw ex; } } } 来提升我的Redux项目,我有以下选项:

Convert.ChangeType

在JS中,我使用webpack-dev-server v1.10.1中的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} 来生成HTTP GET调用

request

但是我收到了CORS错误:

superagent

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

5 个答案:

答案 0 :(得分:25)

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

答案 1 :(得分:17)

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

文档链接

答案 2 :(得分:6)

您从localhost:5050开始运行JavaScript,但您的API服务器是localhost:8000。这违反了相同的原始政策,因此浏览器不允许这样做。

您可以修改您的API服务器以便CORS is enabled,也可以按照"结合现有服务器"下的the instructions on the webpack-dev-server page进行操作。将资产服务与webpack-dev-server和您自己的API服务器结合起来。

答案 3 :(得分:2)

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

答案 4 :(得分:0)

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

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