javascript - Angular 应用程序 $http 请求本地主机上的 Node 应用程序

标签 javascript angularjs node.js

我正在 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 ),我看到了这个...

enter image description here

但由于某种原因,响应选项卡为空。当我使用浏览器和 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/

相关文章:

javascript - PHP、AJAX 和服务器客户端的挫败感

node.js - 如何模块化 AngularJS 应用程序/插件

javascript - 防止 html onclick、onmouseout 中的 xss,...用于 SPA

mysql - 继承多对多关系 : Cannot read property 'split' of undefined

javascript - 为什么在执行递归回调时 .foreach 的行为与 for...of 不同?

javascript - rails 5 : Trying to render divs with a single partial but keep the div class unique so that JQuery doesn't fire on all partials

javascript - 如何在新的 React Router v4 中访问历史对象

angularjs - 在新的@angular/router 3.0.0-alpha.3 中找不到 provideRouter 和 RouterConfig^

javascript - webpack-dev-server npm run dev 抛出 TypeError : Cannot set property 'port' of undefined

node.js - NodeJs错误: Cannot GET/admin when using router