2016-03-15 26 views
2

一個網站正在做一個XMLHttpRequest我節點的應用程序,但他們得到以下錯誤:CORS在我的節點的應用程序不能正常工作

XMLHttpRequest cannot load http://[MY IP]/start. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.[THEIR WEBSITE].com' is therefore not allowed access. The response had HTTP status code 504. 

這是他們的XMLHttpRequest請求:

var xhr = typeof XMLHttpRequest === "undefined" ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest; 
xhr.open("POST", 'http://[MY IP]/myapp', true); 
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
xhr.send(JSON.stringify(data)); 

這是節點應用程序中的代碼(...代表不相關的代碼):

... 
var cors = require('cors') 
... 
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', 'GET,POST'); 
    next(); 
}); 

app.post('/myapp', function (req, res) { 
    var data = req.body; 
    console.log(data); 
    res.status(200); 
}); 

你知道爲什麼這不是加工?

感謝您的建議。

+0

爲什麼你不利用CORS庫? –

+0

我是? VAR CORS =需要( 'CORS') –

回答

0

嘗試增加OPTIONS作爲允許的方法之一。

基本上與res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST');

+0

感謝您的答覆。我試過這個,但我仍然有同樣的問題。我的應用程序背後是一個nginx反向代理。這可能會影響事情嗎? –

+0

可能。你可以發佈你的應用程序從服務器獲取的標題嗎? – limbuster

+0

迴應爲空。我得到一個504(超時)錯誤。但是,如果我嘗試使用簡單的GET請求來訪問我的節點應用程序,它可以正常工作。奇怪... –

1

更換res.header('Access-Control-Allow-Methods', 'GET,POST');我是誰創造了這個問題的人。

我想出答案。

如果一個XMLHttpRequest打開請求被設置爲異步(第三個參數設置爲「真」)時,節點應用必須發送響應。狀態碼是不夠的。你必須提供某種迴應。否則,你會得到一個504超時錯誤。

編輯:你可以使用res.sendStatus(200)。我的錯誤是我只是在做res.status(200)。