Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Cannot send POST request with appropiate CORS headers

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

like image 270
Jorge Arévalo Avatar asked Jun 06 '14 13:06

Jorge Arévalo


People also ask

What is HTTP POST in AngularJS?

AngularJS Http Post ($http.post ()) service In angularjs we use $http service to send or get data from remote http servers using browsers XMLHttpRequest object.

How to send or get data from remote HTTP server in AngularJS?

In angularjs we use $http service to send or get data from remote http servers using browsers XMLHttpRequest object.

What is service not exists in AngularJS?

If you observe above output we got message like " Service not Exists " that means the url which we defined in angularjs $http.post () method not exists that's why it's showing error message. In case if service exists with that url it will execute and will show message like " Post Data Submitted Successfully ".

How do you do Cors in Express applications?

That's how I do CORS in express applications, you have to remember about OPTIONS because for some frameworks there are 2 calls for CORS, first one is OPTIONS which checks what methods are available and then there is actual call, OPTIONS require just empty answer 200 OK Show activity on this post.


2 Answers

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

like image 138
Dayan Moreno Leon Avatar answered Oct 14 '22 06:10

Dayan Moreno Leon


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

like image 22
shubhu Avatar answered Oct 14 '22 06:10

shubhu