AngularJS sends OPTIONS instead of POST

I am stuck in these 2 days, I can not find a solution. When I do AngularJS POST, it sends OPTIONS to the header and returns an API error, the code looks like 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 included in the API, it has Headers, when I do POST with fiddler or POSTMan in Chrome, it works fine only when I use post angularJS, it will not go through.

Why am I getting OPTIONS /SubmitTicket HTTP/1.1 instead of POST?

What do I need to do with POST? I read about it, it says something like CORS, adding the OPTIONS header, but why?

+5
source share
4 answers

When you call CORS requests, the browser always sends an OPTIONS request to the server to find out which methods are actually allowed. So this is the desired behavior. This is called: "Pre-sold request", see: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ (section: " Pre-Lighting Requests ")

Therefore, in your case, you must enable the OPTIONS method in the "Access-Control-Allow-Methods" header of your CORS filter.

+1
source

I understand that angular initially sends an OPTIONS request to the server to ask the server if the full request is allowed. The server will then respond with headers, indicating what is and is not allowed.

I assume this could be a problem when the server returns invalid CORS headers. You said that the server returns an error, please write this error here.

See the CORS preview request at: http://www.staticapps.org/articles/cross-domain-requests-with-cors and also AngularJS performs an OPTIONS HTTP request for the cross source

+1
source

// A simple example of a POST request (data transfer):

 $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. }); 
0
source

You only need to execute this code to make it 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); 
0
source

All Articles