Solving No Access-Control-Allow-Origin with Node js and Express

S

If you are receiving an error similar to XMLHttpRequest cannot load localhost:3000. No Access-Control-Allow-Origin header is present on the requested resource. Origin localhost:8888 is therefore not allowed access. This typically implies that you need to enable CORS on your Node js server that is running Express as the web server. Example code below.

No Access-Control-Allow-Origin header is present

CORS stands for Cross Origin Resource Sharing which means one website cannot perform an AJAX request against it if the server being called does not have CORS enabled. The solution involves add cors to express. In the above example, I have Apache running a web server on port 8888 and I have Node.js with Express running on port 3000 with cors npm. When I make a request from the 8888 website to the 3000 website as a security measure the Node.js server is preventing the request because I have not explicitly allowed other websites to perform AJAX requests. This CORS issue often goes hand-in-hand with the other most common Express error of cannot set headers after they are sent to the client where I describe 3 most likely reasons this error is occurring. cors policy: no ‘access-control-allow-origin’ header is present on the requested resource or xhr access-control-allow-origin with the missing allow origin header.

This error can might also look like:

  • referenceerror: cors is not defined
  • access to xmlhttprequest at ‘http //localhost
  • access-control-allow-origin not working
  • access-control-expose-headers nodejs
  • express access-control-allow-origin: *

To allow this, you need to turn CORS on when you instantiate your Express server as follows:

cors policy no ‘access-control-allow-origin’

[code]
app.use(function (req, res, next) {

res.setHeader(‘Access-Control-Allow-Origin’, ‘http://localhost:8888’);
res.setHeader(‘Access-Control-Allow-Methods’, ‘GET, POST, OPTIONS, PUT, PATCH, DELETE’);
res.setHeader(‘Access-Control-Allow-Headers’, ‘X-Requested-With,content-type’);
res.setHeader(‘Access-Control-Allow-Credentials’, true);

next();
});
[/code]

In the above code it explicitly defines what websites can perform an AJAX request. You can also allow/prevent specific HTTP methods has been blocked by cors policy: no ‘access-control-allow-origin’ header is present on the requested resource. E.g. only allow a read aka GET request. In a production scenario, the Allow-Origin would be actual domain names that you want to allow.

Has been blocked by cors policy: no ‘access-control-allow-origin’ header is present on the requested resource

You can also allow any by setting the Allow-Origin to * when using express.js cors.

How to fix cors in Express?

And of course someone has built an npm CORS package if you prefer to not write your own to solve access-control-allow-origin javascript.

About the author

By Jamie

My Books