首页 >社区问答列表 >javascript - 为什么jQuery可以正常请求,angularjs却报跨域错误?

javascript - 为什么jQuery可以正常请求,angularjs却报跨域错误?

报 XMLHttpRequest cannot load http://example.com/v1/recharge. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

   recharge.createRecharge = function (
          operatorId, operatorName, amount, extraAmount, userId, userName) {
          var deferred = $q.defer();
          var data = {
            operator: {
              user_id: operatorId,
              user_name: operatorName
            },
            amount: amount,
            recharge_amount: amount + extraAmount,
            currency: 'SGD',
            user: {
              user_id: userId,
              user_name: userName
            }
          };

          data = angular.toJson(data);
          if (data) {
            $http({
              method: 'POST',
              url: 'example.com/v1/recharge',
              headers: {
                'Content-Type': 'application/json'
              },
              data: data
            })
              .success(function (d, status) {
                  deferred.resolve(d, status);
                }
              ).error(function (err, status) {
              console.log(err);
            });
          }

          return deferred.promise;
        };
        

下面这个却可以,

 var data = {
          'operator': {'user_id': '4320-9962-1b83f8fc4264', 'user_name': '乱石铺街'},
          'amount': 1,
          'recharge_amount': 2,
          'currency': 'SGD',
          'user': {'user_id': '4b92-ad75-506590099de5', 'user_name': 'ssdss'}
        };
        $.ajax({
          url: 'example.com/v1/recharge',
          method: 'POST',
          dataType: 'json',
          headers:{'Content-Type': 'application/json'},
          data: JSON.stringify(data),
          success: function (data) {
            alert(JSON.stringify(data));
          }
        });           

  • 我想大声告诉你
  • 我想大声告诉你    2017-06-15 09:24:531楼

    那得看看你 "REWARDS_SERVICE_HOST"这个值是什么了,你下面ajax中的url很明显是相对路径,请求的是本地项目的接口地址。

    但是如果你的"REWARDS_SERVICE_HOST"里面带上了http://.../v1 而http://.../并不是完全和你项目的域名端口一致的话,那么就会报跨域啊

    +0添加回复

  • 回复