Follow @endyourif rss Facebook LinkedIn

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

Published on Feb 24, 2020

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. 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. 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.

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

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


In the above code it explicitly defines what websites can perform an AJAX request. You can also allow/prevent specific HTTP methods. 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.

You can also allow any by setting the Allow-Origin to *.

And of course someone has built an npm CORS package if you prefer to not write your own.

Tags: Node js Tutorial | express

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP