Using webpack to proxy to your local web server to avoid Cross Site errors

Datetime:2016-08-23 00:26:30          Topic: Webpack           Share

You know the pain of this error message I assume…

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

This is caused by Javascript trying to access a web server not on the same origin. For example http://localhost:8080 trying to access http://localhost:3000 .

You can override this by allowing cross origin access, but that’s not usually a good idea.

The best way to go around it is to make your local same as production, your client application and the server are on the same origin.

In production, this is usually handled by Nginx or any other web server, on your local, you can use Webpack in order to achieve this.

So, for example, anything with /api/v5 prefix will be proxied to your web server.

In your devServer segment of your webpack.config.js you can simply add this:

proxy: {
      '/api/v5*': 'http://localhost:3000'
    }

This basically means that whenever you have a request going to /api/v5/something it will be proxied through your local web server (Rails in my case).

Like so:

fetch('/api/v5/tribes/index.json').then(res => res.json()).then(function(response) {
    // REDACTED...

You can have multiple proxies (imagine services doing different things) as well.

Hope this helps, enjoy!





About List