Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack dev server CORS issue

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

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


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.


Had the same issue, but my api was on a https protocol (https://api....). Had to start the server with https and use https://localhost:8080

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

There are 2 solutions for this. first one is setting up proxy on the client side, second one is setting CORS on the server. CORS is server issue, server does not allow access from different source. Even using different ports is considered to be different source

First Solution

IN your backend code, you have to set this headers: this is example of in 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();
});

Second Solution:

in webpack config.js, if you want to pass any variable, we export

module.exports=function(env){
return {}} 

instead of

module.exports={}

we inject this env through the script.

"dev-server": "webpack-dev-server --env.api='https://jsonplaceholder.typicode.com/users'",

now webpack has access to this env. in 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);
            }
          },
        },
      },
    },
    
  };
};