問題描述
我正在嘗試從backbone.js 獲取到我的node.js 服務器.但是,我在控制臺中收到以下錯誤:
I'm trying to do a fetch from backbone.js to my node.js server. However, I get the following error in the console:
Access-Control-Allow-Origin 不允許訪問源 http://localhost.
我將以下內容添加到我的 node.js 服務器:
I added the following to my node.js server:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
};
app.configure(function() {
app.use(allowCrossDomain);
});
但它仍然返回相同的錯誤.但是,即使這確實有效,它似乎也不是理想的解決方案,因為我希望來自世界各地的用戶都能夠發送請求.
But it's still returning the same error. However, even if this did work, it doesn't seem like the ideal solution, as I would like users from all over to be able to send requests.
推薦答案
如果你希望每個人都能訪問 Node 應用,那么嘗試使用
If you want everyone to be able to access the Node app, then try using
res.header('Access-Control-Allow-Origin', "*")
這將允許來自任何來源的請求.CORS enable 站點有很多關于不同的 Access-Control-Allow 標頭以及如何使用它們的信息.
That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.
我使用的是 Chrome,請查看 this 關于 localhost 和 Access-Control-Allow-Origin 的錯誤錯誤.還有另一個 StackOverflow 問題詳細說明了這個問題.
I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.
這篇關于Access-Control-Allow-Origin 不允許來源 http://localhost的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!