Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow CORS for PUT in Node.js

I am trying to make a PUT call to my rest api endpoint, and getting this error:

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

I enabled CORS using this solution: enable-cors, it works for POST.

How do I achieve the same for PUT?

Thanks.

like image 937
Akshay Khot Avatar asked Feb 26 '17 00:02

Akshay Khot


People also ask

Does CORS work with put?

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.

How do I resolve cross-origin issues in Node js?

To solve this error, we need to add the CORS header to the server and give https://www.section.io access to the server response. Include the following in your index. js file. const cors = require('cors'); app.

Does node have CORS?

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.


1 Answers

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();
    });
like image 153
Julien Avatar answered Oct 13 '22 00:10

Julien