2016-11-10 1 views
0

게시물을 보낼 때마다 수동으로 언급하지 않고 백엔드에 보내는 모든 http http.post()에 대해 ipAddress을 보낼 수 있기를 원했습니다. 각성시키는 방법? jQuery에 $ajax.setup이 있다는 것을 알았습니까? js와 비슷한 것을하기위한 예제를 제게 제공해 주시겠습니까?

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

답변

0

당신은 다음과 같은 런타임에서 HTTP 헤더에 ipAddress을 설정할 수 있습니다

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

또는 모든 요청에 ​​HTTP 헤더에 추가, 이러한 기본값은 완전히 $httpProvider.defaults.headers 구성 개체에 액세스하여 구성 할 수 있습니다 현재이 기본 구성을 포함하고 있습니다.

자세한 내용은 $http 서비스의 Setting 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> 
관련 문제