2017-02-26 60 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

相關問題