I'm creating a web app using AngularJS. To test it, I'm running the app in a NodeJS server, using angular-seed template.
In this app, I need to send a JSON message to another host, via POST request, and get the response, so, I'm using CORS.
My request is done by implementing a service that uses AngularJS http service (I need the level of abstraction that $http provides. So, I don't use $resource).
Here, my code. Please pay attention to the fact that I modify $httpProvider to tell AngularJS to send its requests with the appropriate CORS headers.
angular.module('myapp.services', []). // Enable AngularJS to send its requests with the appropriate CORS headers // globally for the whole app: config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; /** * Just setting useXDomain to true is not enough. AJAX request are also * send with the X-Requested-With header, which indicate them as being * AJAX. Removing the header is necessary, so the server is not * rejecting the incoming request. **/ delete $httpProvider.defaults.headers.common['X-Requested-With']; } ]). factory('myService', function($http) { return { getResponse: function() { var exampleCommand = JSON.stringify({"foo": "bar"}); // This really doesn't make a difference /* var config = {headers: { 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Accept', 'Content-Type': 'application/json' } }; */ //return $http.post(REMOTE_HOST, exampleCommand, config). return $http.post(REMOTE_HOST, exampleCommand). success(function(data, status, headers, config) { console.log(data); return data; }). error(function (data, status, headers, config) { return {'error': status}; }); } } }); The problem is I can't make it work. I always get this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at REMOTE_HOST. This can be fixed by moving the resource to the same domain or enabling CORS.
But if I do a simple jQuery AJAX call like this:
$.ajax(REMOTE_HOST, { dataType: "json", type: "POST", data: exampleCommand, success: function(data) { console.log(data); }, error: function(request, textStatus, errorThrown) { console.log("error " + textStatus + ": " + errorThrown);} }); It works fine.
So, my questions:
- How do I allow cross-site requests in an AngularJS running under NodeJS?
UPDATE: Thanks to Dayan Moreno Leon's response.
My problem is I need to add cors support to my server. I'm using NodeJS http-server for development and lighttpd for production.
- Why does the simple jQuery POST request work but AngularJS POST request doesn't?
I guess jQuery AJAX requests are cross-domain by default. Not really sure yet.
Many thanks in advance
useXDomainin Angular. It never made into the Angular code. github.com/angular/angular.js/issues/2956