CORS for PUT

If your server is running on localhost:3000, and you try to make an api call from localhost: 9000, you will get No Access-Control-Allow-Origin header present error. To get rid of this error, we need to enable CORS on the server. How do we do that?

To get rid of the above error, just go to your app.js or the server, and add following code:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

For more details, check out enable-cors.

Above code fixes the issue for GET and POST calls, but if you try to do a PUT, you will get following error:

Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

Turns out we need to add Access-Control-Allow-Methods property in the above object. As seen in preflighted requests, any request other than GET, HEAD, and POST will be preflighted as they are not safe(can modify the data).

So to enable CORS for `PUT, we just need to add following to the above code:

    
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT"); // ["PUT", "DELETE"] if more than one
    next();
})

Written on February 25, 2017