6

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?

10
  • try using $http.put Commented Jun 8, 2015 at 8:25
  • @Mico Sends OPTIONS again.. Commented Jun 8, 2015 at 8:28
  • The HTTP methods POST and PUT aren't the HTTP equivalent of the CRUD's create and update. They both serve a different purpose. It's quite possible, valid and even preferred in some occasions, to use POST to create resources, or use PUT to update resources. Commented Jun 8, 2015 at 8:30
  • @Mico I just want to send JSON object and get a JSON object in return.. :/ Commented Jun 8, 2015 at 8:31
  • 4
    Don't stringify the data... Angular does that for you!! $http.post(URL, JSON.stringify(data)). should be $http.post(URL, data). and don't set the Content-Type, angular also does this for you... Commented Jun 8, 2015 at 8:32

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have this in my API web config: <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" /> Is this enough?
It might be. Be aware that from the security point of view, you have to enable only this options that are you actually using in your API. I usually have GET, PUT, POST and of course OPTIONS.
1

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

7 Comments

It only says Error 500, "Server Error Occured" how do i handle the OPTIONS request? that is something i don't get..
Make sure the API returns the following header 'Access-Control-Allow-Origin: *' (to accept CORS from all sources) or 'Access-Control-Allow-Origin: the address of your client'
indeed i have that too: <add name="Access-Control-Allow-Origin" value="*" />
I had similar problems setting up a go backend API and angular. The solution was to bypass the default request router and dispatcher for OPTION requests. These where the headers i ended up returning Access-Control-Allow-Origin : <origin> Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Just aded thes to the API Web Config?
|
0

// 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.
  });

1 Comment

@Callum Linington Updated My Sample
0

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);

5 Comments

var TestApp= angular.module("TestApp", ['ngRoute', 'ngCookies', 'someService']); Is this the right way to pull it into the controller?
well, no... have you used much of angular before?
var MyController= function ($scope, $http, $location, $cookies, $cookieStore, $interval, $routeParams, someService) I googled it, but now it says: Unknown provider: $someServiceProvider <- $someService <- MyController, what mI doing wrong? :/
can you not show your code? place it in the original question, feel free to change things that are client sensitive..
Unknown provider: someServiceProvider <- someService <- myController, well they kinda are sensitive.. but i will try..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.