I try to send and receive data from HTML page with Angular.js and locally running Node.js server
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>
then I get error:
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.
I try to apply headers as app.js
var app = angular.module('MyTutorialApp', [], function($httpProvider) {
$httpProvider.defaults.headers.post['Access-Control-Allow-Origin'] = 'http://127.0.0.1:1337/';
});
but that does not take effect.
Node.js code
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/');