【问题标题】:XMLHttpRequest cannot load http://127.0.0.1:1337/. No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]XMLHttpRequest 无法加载 http://127.0.0.1:1337/。请求的资源上不存在“Access-Control-Allow-Origin”标头[重复]
【发布时间】:2014-12-15 08:31:57
【问题描述】:

我尝试使用 Angular.js 和本地运行的 Node.js 服务器从 HTML 页面发送和接收数据

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>

然后我得到错误:

 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/');

【问题讨论】:

    标签: node.js angularjs http xmlhttprequest cors


    【解决方案1】:

    如果您使用 Angular 向您的 localhost node.js 服务器发送 ajax 请求,您应该将 access-control-allow-origin 放在接受 ajax 请求的目标服务器上,即 localhost,不要将其与 ajax 请求一起发布。

    【讨论】:

      猜你喜欢
      • 2016-10-10
      • 2013-12-02
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多