angularJS sending OPTIONS instead of POST

9k views Asked by At

Im stuck at this 2 days I can not find a solution. When im doing an AngularJS POST it Sends OPTIONS in the header and returns error from the API the code looks like this nothing special.

$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post(URL, JSON.stringify(data)).
    success(function(data, status, headers, config) {
        alert(data);
    error(function(data, status, headers, config) {
        console.log("Error");
});

CORS is enabled on the API it has the Headers, when i do POST with fiddler or POSTMan in Chrome it works fine only when i use angularJS post it won't go thru.

why do i get OPTIONS /SubmitTicket HTTP/1.1 instead of POST?

What do i need to do to POST ? I have read about it it says something like CORS is adding OPTIONS header but why?

4

There are 4 answers

2
Thomas Weglinski On BEST ANSWER

When you invoke the CORS requests, the browser always sends the OPTIONS request to server to know what methods are actually allowed. So this is the desired behaviour. This is so called: "Preflighted request", see: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ (section: "Preflighted requests")

Therefore in your case, you have to allow the OPTIONS method in 'Access-Control-Allow-Methods' header of your CORS filter.

1
Shian JA On

// Simple POST request example (passing data) :

$http.post('/someUrl', {msg:'hello word!'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
5
Callum Linington On

Should only need to do this code to get it to work:

angular.module('TestApp', [])
   .factory('someService', ['$http', someService]);

function someService() {
  var service = {
    save: save
  };

  var serviceUrl = '/some/Url';

  return service;

  function save(data) {
    $http.post(serviceUrl, data)
          .success(function(data, status, headers, config) {
              alert(data);
          })
          .error(function(data, status, headers, config) {
              console.log("Error");
          });
  }
}

Then pull your someService into your controller and use:

someService.save(data);
7
Kiachma On

My understanding is that angular initially sends an OPTIONS request to the server in order to ask the server if the full request is permissable. The server will then respond with Headers specifying what is and is not allowed.

I guess this might be an issue with the server returning the wrong CORS headers. You said that the server returns an error please post that error here.

See Preflighted CORS request at: http://www.staticapps.org/articles/cross-domain-requests-with-cors and AngularJS performs an OPTIONS HTTP request for a cross-origin resource