webpack dev server CORS issue

2019-02-04 11:21发布

问题:

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}

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
                            }
                        }
                    });
                }
          });

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

回答1:

With webpack-dev-server 1.15.X you can use this configuration in your config file:

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': ''
         }
      }
   }
},

With this example you will redirect all calls from http://0.0.0.0:8888/api/* to http://0.0.0.0:8080/* and CORS solved



回答2:

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

Doc links

  • Webpack dev server
  • Access-Control-Allow-Headers
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Origin


回答3:

You're running your JavaScript from localhost:5050 but your API server is localhost:8000. This violates the same origin policy, so the browser disallows it.

You can either modify your API server so that CORS is enabled, or follow the instructions on the webpack-dev-server page under "Combining with an existing server" to combine asset serving with webpack-dev-server and your own API server.