我尝试使用Angular.js从HTML页面发送和接收数据,并在本地运行Node.js服务器
app.controller("MainController", function MainController($scope, $http){
$scope.postIt = function() {
//alert("posting...");
$http.post('http://127.0.0.1:1337/', {msg:'hello from Angular.js!'})
.success(function onSuccess(response){
console.log(response);
$scope.$apply(function(){
$scope.testData = JSON.parse(response);
console.log($scope.testData);
});
}).error(function onError(){
console.log("AJAX failed!");
});
};
});

<div id='content'
ng-app='MyTutorialApp'
ng-controller='MainController'>
<p>
<a ng-click="postIt()">
Click here to load data.
</a>
</p>
</div>
<script src="bower_components/angular/angular.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>
&#13;
然后我收到错误:
XMLHttpRequest cannot load http://127.0.0.1:1337/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
我尝试将标头应用为app.js
var app = angular.module('MyTutorialApp', [], function($httpProvider) {
$httpProvider.defaults.headers.post['Access-Control-Allow-Origin'] = 'http://127.0.0.1:1337/';
});
但这没有生效。
Node.js代码
var http = require('http');
http.createServer(function handler(req, res) {
console.log(req.method, req.url, req.httpVersion, req.headers);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from Node.js\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
答案 0 :(得分:2)
如果你使用angular来向你的localhost node.js服务器发送ajax请求,你应该把access-control-allow-origin放在接受ajax请求的目标服务器上,即localhost,不要用ajax发布它请求。