angular色应用$ http请求到本地主机上的节点应用
我在localhost:3000上运行nodejs应用程序。 我有一个前端教程的angular度页面,像这样调用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
variables最终看起来像这样…
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 ,是由于同源政策而发生的。 您的节点应用在localhost:3000
上运行,而您的客户端在localhost:9000
。
您需要在服务器端设置Access-Control-Allow-Origin
标头,以允许来自localhost:9000
请求。
确保您的服务器使用正确的内容types标题进行回复:
Content-Type:application/json; charset=utf-8