AngularJS: Cannot send POST request with appropiate CORS headers

11,538

Solution 1

CORS is not handled on the client but in the server you need to allow CORS on your nodejs app where your angular app is trying to POST. you can try using cors module if you are using express

https://www.npmjs.org/package/cors

other whise you need to check for the options method and return 200 as a response

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Solution 2

Why does the simple jQuery POST request work but AngularJS POST request doesn't?

jQuery uses simple requests while AngularJS uses preflighted requests

In your angular code you can add set Content-Type to application/x-www-form-urlencoded and encode your data using $.param

Share:
11,538
Jorge Arévalo
Author by

Jorge Arévalo

I'm a Python/Django developer with a previous background in OpenSource GIS

Updated on June 04, 2022

Comments

  • Jorge Arévalo
    Jorge Arévalo almost 2 years

    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