search

Home  >  Q&A  >  body text

angular.js - Both $http.post() and $http() cross-domain (CORS) requests failed when jquery cross-domain was successful.

For this cors cross-domain resource, the request using jquery is successful.
(The commented out code below is successful)

//var url = "http://test.shenmawo.com.cn/wechat/huodong/h22/giveGift";
//
//$.ajax({
//    type : 'post',
//    url : url,
//    data : {
//
//    },
//    dataType : "json",
//    success : function(data, status) {
//        $scope.prize = data;
//    },
//    error : function(data, status, e) {
//        console.log("系统异常" + e);
//    }
//});

But $http.post of angularjs is unsuccessful:

$http
.post('http://test.shenmawo.com.cn/wechat/huodong/h22/giveGift', {})
.success(function(data){
    $scope.prize = data;
})
.error(function(err){
    alert(err);
});

Using $http([Object]) also fails:

//$http({
//    url:'http://test.shenmawo.com.cn/wechat/huodong/h22/giveGift',
//    method:'POST',
//    data: {},
//    withCredentials:true,
//    success: function(data){
//      $scope.prize = data;
//    },
//    err:function(err){
//        alert(err);
//    }
//});

In addition, I also added the configuration according to the searched requirements:

angular.module('zil',['ngRoute'])
.config(['$routeProvider', '$httpProvider',function($routeProvider, $httpProvider){
    $httpProvider.defaults.useXDomain = true;//添加的配置
    $routeProvider
       .when('/',{……})
       .when('/game',{
           templateUrl:XXX,
           controller:function(){
               /*上面所有跨域请求的代码都位于这个位置*/
           }
       });

How can I use angularjs to make cross-domain requests?

世界只因有你世界只因有你2774 days ago833

reply all(1)I'll reply

  • 某草草

    某草草2017-05-15 16:53:02

    postCfg = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      transformRequest: function(data) {
        return $.param(data);
      }
    }
    
    app.config([
      '$httpProvider',
      function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
       }
    ]}
    
    $http.post(url, {}, postCfg)

    The method I just found, the speed test was successful

    reply
    0
  • Cancelreply