2017-02-26 58 views
2

我试图做一个PUT调用我的REST API端点,并收到此错误:节点:允许CORS的PUT

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

我使用该解决方案使CORSenable-cors,它为POST

如何达到PUT的相同?

感谢。

+1

难道你阅读错误信息? https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Methods – SLaks

+2

你需要添加PUT(可能是OPTIONS)到'Access-Control-Allow-Methods' header –

+0

谢谢@SLaks和Jaromanda,我在我的头文件中添加了'PUT':'res.header(“Access-Control-Allow-Methods”,“PUT”);'。有效。 – akshayKhot

回答

5

补充一点:

res.header( '访问控制允许的方法', '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

您需要支持OPTIONS方法您的服务器上,因为浏览器将飞行前所有跨域PUT请求,不管你有什么头。而且,你需要确保你明确地允许PUT在你的CORS头文件中。从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.

所以,在你的服务器,你需要做这样的事情:

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

下面是对主题的文章:

Cross-Origin Requests in Express.JS

相关问题