【发布时间】:2016-05-18 06:23:39
【问题描述】:
我正在 localhost:3000 上运行 nodejs 应用程序。我有一个前端教程角度页面,它像这样调用 localhost...
$scope.msg = 'requesting';
$http({
method: 'GET',
url: 'http://localhost:3000/'
}).then(function(response) {
$scope.msg = response;
}, function(response) {
$scope.msg = 'err ' + JSON.stringify(response);
});
我可以从我的节点应用程序的控制台中看到它正在回答 200 和一个 json 对象 {foo:'bar'}。但是$scope.msg 变量最终看起来像这样......
err {
"data":null,
"status":-1,
"config":{
"method":"GET",
"transformRequest":[
null
],
"transformResponse":[
null
],
"url":"http://localhost:3000/",
"headers":{
"Accept":"application/json, text/plain, */*"
}
},
"statusText":""
}
为什么当服务器产生良好的响应时客户端会认为有问题?在浏览器中运行请求可以正常工作。
正在加载 Angular 页面 (http://localhost:9000) 浏览器开发工具,我看到了这个...
但由于某种原因,响应选项卡是空的。当我使用浏览器发出相同的请求 (http://localhost:3000/) 并观看时,我会在响应选项卡中看到 JSON。
【问题讨论】:
-
您在浏览器控制台中看到了什么?你在反对同源政策吗?
-
@SLaks 做同一个主机,不同的端口算作同一个来源?
-
@SLaks...啊。控制台!是的,它确实表明“请求的资源上存在 Access-Control-Allow-Origin 标头。...因此是不允许的。我现在要去谷歌看看我是否可以学习如何修复。谢谢有用的提示。
-
基本上你需要在服务器端将
Access-Control-Allow-Origin标头设置为localhost:9000。 (不过,如果你只在 localhost 上而不是公开地托管它,你可以将它设置为*。) -
@JohnSmith - 很大的帮助,谢谢!你想把它作为一个答案让我检查一下吗?
标签: javascript angularjs node.js