Allow CORS for PUT in Node.js Allow CORS for PUT in Node.js express express

Allow CORS for PUT in Node.js


add this:

res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

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, POST, GET, DELETE, OPTIONS');          next();    });


You will need to support the OPTIONS method on your server because the browser will pre-flight all cross-origin PUT requests, no matter what headers you have. And, you need to make sure you're explicitly allowing PUT in your CORS headers. See this from MDN's page on CORS:

Additionally, for HTTP request methods that can cause side-effects on server's data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

So, in your server, you would need to do something like this:

app.use(function(req, res, next) {    res.header('Access-Control-Allow-Origin', '*');    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');    // allow preflight    if (req.method === 'OPTIONS') {        res.send(200);    } else {        next();    }});

Here's an article on the topic:

Cross-Origin Requests in Express.JS