2016-11-10 78 views
0

我希望能够发送ipAddress每个$ http.post()这是发送到后端没有手动提到每次我发送帖子。如何在角度做?我发现在jQuery中有$ajax.setup可以请你给我提供一个在angularjs中做类似的例子吗?

$http.post('actions.php', {ip: ipAddress, data: add}) 
     .then(function (response) { 
      alert("post sent") 
     }); 

回答

0

您可以设置ipAddress在HTTP标头在运行时是这样的:

module.run(function($http) { 
    $http.defaults.headers.common.IpAddress = ipAddress; 
}); 

或将其添加到HTTP标头所有请求,这些默认值可以完全通过访问$httpProvider.defaults.headers配置对象配置,它当前包含这个默认配置。

欲了解更多信息,请检查$httpSetting HTTP Headers部分Angular docs服务部分。

0

您可以创建自定义的“$ http”工厂,将您的自定义数据添加到每个请求。

angular.module('app', []) 
.factory('myHttp', ['$http', function($http) 
{ 
    return function(method, url, args) 
    { 
     var data = angular.extend({ip: '127.0.0.1'}, args); 

     return $http[method](url, data); 
    }; 
}]) 
.controller('myCtrl', function($http, myHttp) 
{ 
    myHttp('post', 'actions.php', {a: 'a'}) 
     .then(function(response) 
     { 
      alert("post send"); 
     }); 
}); 
0

您可以使用$ http拦截器。你可以将你的拦截器添加到$ httpProvider。它将被要求每个$ http请求。您可以将您的逻辑添加到拦截器的请求方法中。看到一些用法here

0

这将工作。首先使用get方法捕获客户端的IP地址,然后使用post方法发送它。

<script> 
     var app = angular.module('myApp', []); 
     app.controller('ctrl', function($scope, $http) { 
      var json = 'http://ipv4.myexternalip.com/json'; 
      $http.get(json).then(function(result) { 
       var ip_addr=result.data.ip; 
       var config = { 
        headers : { 
         'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
        } 
       } 
       $http.post('actions.php', ip_addr, config) 
        .success(function (data, status, headers, config) { 
        $scope.PostDataResponse = data; 
       }) 
       console.log(ip_addr); 
      }, function(e) { 
       alert("error"); 
      }); 
     }); 

    </script>