Why does a cross-domain angularjs $http.post request fail when a XMLHttpRequest succeeds?

前端 未结 6 409
情歌与酒
情歌与酒 2021-02-01 10:32

I am trying to exercise the Trello API with an application key and token from an angular (version 1.0.5) webapp. The server seems correctly configured to handle CORS. A test req

相关标签:
6条回答
  • 2021-02-01 11:12

    To avoid this issue, create a function in the server side to catch the 'OPTIONS' and just return true. Some thing as follows.

        /**
         * @url OPTIONS /
         */
        public function options()
        {
            return;
        }
    
    0 讨论(0)
  • 2021-02-01 11:24

    Add the headers param to the $http and you'll be fine.

              var config = {
                method: 'POST',
                url: 'your url',
                headers: {
                  'Content-Type': undefined
               },
               data: {
                  "channel": "#fun-and-game",
                  "username": $scope.question.title,
                  "text": $scope.question.text,
                  "icon_emoji": ":ghost:"
              },
           };
    
          $http(config).success(function(data) {
             $scope.server_resp = data;
          }).error(function(response) {
    
          });
    

    for more info, check angularjs $http docs

    0 讨论(0)
  • 2021-02-01 11:24

    As per this angular pull request, CORS can be made to work by deleting X-Requested-With which causes a pre-flight OPTIONS request:

    App.config(['$httpProvider', function($httpProvider) {
        delete $httpProvider.defaults.headers.common["X-Requested-With"];
    }
    

    Note that I have not tried this personally, but a co-worker had to deltete the header to make his CORS request work.

    0 讨论(0)
  • 2021-02-01 11:31

    The 'content-type' header is not accepted by the server and is added by default for Angular $http POST request (see $http doc). You can try to remove it from your $http config. Inject $httpProvider in your controller, then this might work:

    delete $httpProvider.defaults.headers.post['Content-type']
    

    You might have to try with 'content-type' also, I'm not sure of the case to use.

    0 讨论(0)
  • 2021-02-01 11:35

    This worked for me

    $http({
          method  : "POST",
          url     : url,
          data    : $.param({key: 'value', key2 : 'value'}),
          headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
                    })
    
    0 讨论(0)
  • 2021-02-01 11:37

    I just ran into a similar issue and the problem was that I was getting the url wrong. I was posting to 1/cards/actions/createCard because I missread the docs. I got an access-control related error even though headers etc. look right. Posting to 1/cards created a card, which is what I wanted.

    0 讨论(0)
提交回复
热议问题