我目前正在閱讀Adam Freeman的「Pro AngularJS」。在閱讀示例時,他讓讀者創建了一個使用Angular(當然)和Deployd服務器資源的體育商店應用程序。 Deployd資源設置爲返回要填充到模型中的JSON數據。我正在使用NodeJS來運行我的服務器。它目前安裝在5000端口(http://localhost:5000/sportsstore/app.html
)。 Deployd資源在端口5500上運行(http://localhost:5500/products
)。當打Deployd,響應如下:Deployd - 通過AngularJS檢索的數據CORS
[
{ "name": "Kayak", "description": "A boat for one person", "category": "Watersports", "price": 275, "id": "a1c999fc248b2959" },
{ "name": "Lifejacket", "description": "Protective and fashionable", "category": "Watersports", "price": 48.95, "id": "61303717cfad182e" },
{ "name": "Soccer Ball", "description": "FIFA-approved size and weight", "category": "Soccer", "price": 19.5, "id": "0fb5f67bdcbd992f" },
{ "name": "Corner Flags", "description": "Give your playing field a professional touch", "category": "Soccer", "price": 34.95, "id": "24385d315dd388b4" },
{ "name": "Stadium", "description": "Flat-packed 35,000-seat stadium", "category": "Soccer", "price": 79500, "id": "500fb6805905a856" },
{ "name": "Thinking Cap", "description": "Improve your brain efficiency by 75%", "category": "Chess", "price": 16, "id": "637d8a1f42e6fa1c" },
{ "name": "Unsteady Chair", "description": "Secretly give your opponent a disadvantage", "category": "Chess", "price": 29.95, "id": "73393312ec7dfab7" },
{ "name": "Human Chess Board", "description": "A fun game for the family", "category": "Chess", "price": 75, "id": "7871d02a662b0915" },
{ "name": "Bling-Bling King", "description": "Gold plated, diamon-studded King", "category": "Chess", "price": 1200, "id": "b59a3389a0e248bd" }
]
我試圖通過使用$http.get
來獲取這些數據:
$http.get("http://localhost:5500/products")
.success(function (data) { ... })
.error(function (error) { ... });
然而,這一直返回一個錯誤:
XMLHttpRequest cannot load http://localhost:5500/products. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.
研究表明,Angular和CORS存在/存在一些問題,並且必須將頭配置爲運行跨域請求。其結果是,添加以下到我的app.config:
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With']; // this isn't needed anymore, but was put here as a just-in-case
儘管有這些設置添加,我仍然得到錯誤。 Deployd文檔說它是爲CORS自動配置的(Cross-Origin Requests),只要請求中沒有包含無效的自定義標題,就會發送相應的標題信息。我敢肯定我的請求不包含無效的自定義頁眉:
Accept: application/json, text/plain, */*
Cache-Control: max-age=0
Origin: http://localhost:5000
Referer: http://localhost:5000/sportsstore/app.html
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
我的問題:是否有一些其他的配置,我需要落實到位,纔能有Deployd配置爲允許CORS請求來處理?本書不指定任何特殊的Angular頭文件設置或其他任何內容。
我有完全相同的問題。 – Rob