我正在 localhost:3000 上运行 Nodejs 应用程序。我有一个前端教程 Angular 页面,它像这样调用本地主机...
$scope.msg = 'requesting';
$http({
method: 'GET',
url: 'http://localhost:3000/'
}).then(function(response) {
$scope.msg = response;
}, function(response) {
$scope.msg = 'err ' + JSON.stringify(response);
});
我可以从我的 Node 应用程序的控制台看到它正在回答 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 ),我看到了这个...
但由于某种原因,响应选项卡为空。当我使用浏览器和 watch 发出相同的请求 ( http://localhost:3000/ ) 时,我在响应选项卡中看到 JSON。
最佳答案
正如SLAks在评论中提到的,这是由于同源政策而发生的。您的 Node 应用程序在 localhost:3000
上运行,而您的客户端在 localhost:9000
上运行。
您需要在服务器端设置 Access-Control-Allow-Origin
header 以允许来自 localhost:9000
的请求。
关于javascript - Angular 应用程序 $http 请求本地主机上的 Node 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37286847/