1

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/');
cbass
  • 2,548
  • 2
  • 27
  • 39
Paul Verest
  • 60,022
  • 51
  • 208
  • 332

1 Answers1

2

if you are using angular to send ajax request to your localhost node.js server, you should put access-control-allow-origin on the target server accepting the ajax request i.e. localhost, don't post it with ajax request.

Volkan Ulukut
  • 4,230
  • 1
  • 20
  • 38