2015-11-02 26 views
11

我有我的快遞服務器上http://localhost:3000運行(我稱之爲web服務器) 我有另一個應用程序在本地主機上運行:8100(我把這個簡單的「應用」)獲取Express服務器接受CORS請求

當我的應用程序打電話給Web服務器我收到消息:

"XMLHTTPReqeust cannot load http://localhost:3000/auth/facebook. Response to preflight request doesn't pass access control check. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' when the credentials flag is true. Origin 'http://localhost:81000' is therefore not allowed acecss" 

此消息顯示在瀏覽器控制檯中。

我已經安裝在我的節點的網絡服務器

res.header('Access-Control-Allow-Origin', '*'); 
res.header('Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE'); 

的中間件下列選項讀幾stackoverfow問題後,我還增加了以下內容:

res.header('Access-Control-Allow-Origin', 'http://localhost:8100'); 

然而,這並不解決問題。

+3

您還需要在'Access-Control-Allow-Methods'中允許'OPTIONS'方法 –

回答

13

我個人比較喜歡cors模塊。代碼非常簡單:

var whitelist = [ 
    'http://0.0.0.0:3000', 
]; 
var corsOptions = { 
    origin: function(origin, callback){ 
     var originIsWhitelisted = whitelist.indexOf(origin) !== -1; 
     callback(null, originIsWhitelisted); 
    }, 
    credentials: true 
}; 
app.use(cors(corsOptions)); 
+3

我建議使用cors模塊,正如托馬斯建議的那樣,而不是處理標題內容。它很容易設置和使用。它需要30秒來解決一般問題。 – user5026837

10

您還需要在標頭中允許OPTIONS方法。

我有這樣的中間件CORS:

module.exports = function (req, res, next) { 
    // CORS headers 
    res.header("Access-Control-Allow-Origin", "YOUR_URL"); // restrict it to the required domain 
    res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"); 
    // Set custom headers for CORS 
    res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header"); 

    if (req.method === "OPTIONS") { 
     return res.status(200).end(); 
    } 

    return next(); 
}; 

PS。你得到的錯誤是由於跨源請求的工作原理。長話短說,瀏覽器可能會首先發送一個pre-flight請求與方法OPTIONS獲得允許的來源,標題和方法。所以對於這個請求,你應該只返回Access-Control-*標題。如果pre-flight沒有問題,瀏覽器將繼續處理原始請求。

你可以找到更多的信息here

4

顯然cors模塊沒有工作。

使用上面我給出的提示,用下面的代碼:

if (req.method === "OPTIONS") { 
    res.header('Access-Control-Allow-Origin', req.headers.origin); 
    } else { 
    res.header('Access-Control-Allow-Origin', '*'); 
    } 

這並獲得成功。

+1

這應該是最佳答案。 –

5

得到了同樣的問題,偶然發現了大約一個小時,溶液呈其實很簡單,只需啓用CORS爲preflight operations

app.options('*', cors()); // include before other routes 
+1

結合runtimeZero if-else代碼,這對我來說非常合適! 更多細節[這裏](https://github.com/expressjs/cors#enabling-cors-pre-flight) – vish213

+1

事實上,CORS的處理需要包含在其他路線幫助很多之前。 –

7

我使用CORS和實現它的話,它是非常簡單的

var cors=require('cors');

app.use(cors({origin:true,credentials: true}));