ExpressJS, AngularJS - Cross domain request issue ExpressJS, AngularJS - Cross domain request issue express express

ExpressJS, AngularJS - Cross domain request issue


This is the CORS browser limitation. Your server will have to response with some headers to tell the browser cross domain access is allowed.

If you search around there are a few middleware as node package (eg. express-cors) available. But I found sometimes they does not work as what I want. So here is the one I used:

app.use(function(req, res, next) {   res.header("Access-Control-Allow-Origin", "*");   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');   res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Cache-Control");   if (req.method === 'OPTIONS') {    res.statusCode = 204;    return res.end();  } else {    return next();  }});

By the way, you will have to use this middleware for the server you are accessing ( http://local.dev:3000/api )

When trying to access a cross origin resource, the browser will try to make a Options request to read these special header and decide if the server allow the access. This is why, for Options request, you can response straight away without passing the flow using 'next()'.

You can also edit the list of methods allow by editing the Access-Control-Allow-Methods header.

Access-Control-Allow-Headers header is optional, you can use it to limit the headers that can be used.