search

Home  >  Q&A  >  body text

javascript - Why can jQuery request normally, but angularjs reports a cross-domain error?

Report 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;
        };
        

The following one works,

 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));
          }
        });           
高洛峰高洛峰2710 days ago687

reply all(1)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-06-15 09:24:53

    Then you have to see what the value of your "REWARDS_SERVICE_HOST" is. The url in your ajax below is obviously a relative path, and the request is the interface address of the local project.

    But if your "REWARDS_SERVICE_HOST" contains http://.../v1 and http://.../ is not completely consistent with the domain name port of your project, then it will be reported as cross-domain

    reply
    0
  • Cancelreply