How to solve CORS issue in XMLHttpRequest by using Node.js?

Posted by Wei Xia on March 16, 2017 | Hits:


I am trying to do API request by using RESTful API, however, I got error message below from console.

XMLHttpRequest cannot load Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘’ that is not equal to the supplied origin. Origin ‘’ is therefore not allowed access.


Add the following code into app.js.

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');


This is the end of post