Allow CORS for PUT in Node.js

一曲冷凌霜 提交于 2020-04-05 15:58:41

问题


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.


回答1:


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();
    });



回答2:


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



来源:https://stackoverflow.com/questions/42463499/allow-cors-for-put-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!