我目前正在阅读 Adam Freeman 的“Pro AngularJS”。在浏览这些示例时,他让读者使用 Angular(当然)和已部署的服务器资源创建一个体育商店应用程序。Deployd 资源设置为返回要填充到模型中的 JSON 数据。我正在使用 NodeJS 来运行我的服务器。它当前设置在端口 5000 ( http://localhost:5000/sportsstore/app.html
) 上。已部署资源在端口 5500 ( http://localhost:5500/products
) 上运行。点击 Deployd 时,响应如下:
[
{ "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
尽管添加了这些设置,但我仍然收到错误消息。已部署的文档说它是为 CORS(跨域请求)自动配置的,只要请求不包含无效的自定义标头,它就会发送适当的标头信息。我很确定我的请求不包含无效的自定义标头:
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 标头设置或其他任何内容。