使用AngularJs从另一个域发出Ajax请求

时间:2014-08-04 14:52:47

标签: node.js angularjs angular-http deployd

我正在使用本书学习AngularJS,我使用Angular,Node,Deployd构建了这个webapp。现在,我的应用程序停留在localhost:5000 / app.html,5000是节点Web服务器侦听的端口。我尝试以这种方式检索存储在deployd中的数据:

$http.get("localhost:5500/products")
    .success(function (data) {
        $scope.data.products = data;
    })
    .error(function (error) {
        $scope.data.error = error;
    });

但是这会导致错误:没有' Access-Control-Allow-Origin'标头出现在请求的资源上。我怎么解决这个问题?谢谢:))

1 个答案:

答案 0 :(得分:3)

凯文B是对的。这是阻止您的请求的同源政策。

您应该在此处执行的操作是将您的请求从客户端发送到您的节点服务器(“/ products”)。在这里,您可以轻松地将它们代理到localhost:5500,例如使用node-http-proxy(https://github.com/nodejitsu/node-http-proxy)。

从node-http-proxy README.md(将主机/端口改为你的用例):

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer(options);
require('http').createServer(function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:5500' });
});

可能会干扰您当前的节点服务器(首先为您提供客户端角度代码)。如果您正在使用Express,可以将“http”和“http-proxy”结合使用,如下所示:https://stackoverflow.com/a/22244101/3651406

相关问题