angularJS sending OPTIONS instead of POST

前端 未结 4 931
一个人的身影
一个人的身影 2021-01-18 08:57

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 no

相关标签:
4条回答
  • 2021-01-18 09:25

    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.

    0 讨论(0)
  • 2021-01-18 09:34

    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

    0 讨论(0)
  • 2021-01-18 09:41

    // 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.
      });
    
    0 讨论(0)
  • 2021-01-18 09:43

    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);
    
    0 讨论(0)
提交回复
热议问题