AngularJS全局修改$ http中每个请求的URL

sub*_*ero 21 angularjs

我们设置一个简单的例子:

$scope.whatDoesTheFoxSay = function(){
    $http.post("/backend/ancientMystery", {
...
Run Code Online (Sandbox Code Playgroud)

如何全局转换发送帖子请求的URL?基本上我想在每个http请求前加一个URL.

我试过的是$rootScope在应用程序启动时在包含url中设置一个变量.但这不是我希望我的代码看起来像:

$scope.whatDoesTheFoxSay = function(){
    $http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", {
...
Run Code Online (Sandbox Code Playgroud)

假设我应该调查,我是否正确$httpProvider.defaults.transformRequest?任何人都可以提供一些基本的示例代码吗?

Aja*_*wal 43

我有另一种使用$ http的请求拦截器的方法,它将处理一个公共位置的所有url

<!doctype html>
<html ng-app="test">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>

  </head>
 <body ng-controller="test" >    


<!-- tabs -->


 <script>
     var app = angular.module('test', []);
     app.config(function ($httpProvider) {
         $httpProvider.interceptors.push(function ($q) {
             return {
                 'request': function (config) {
                     config.url = config.url + '?id=123';
                     return config || $q.when(config);

                 }

             }
         });
     });

     app.controller('test', function ($scope,$http) {
         $http.get('Response.txt').success(function (data) { alert(data) }).error(function (fail) {

         });
     });

   </script>
</body>


</html>
Run Code Online (Sandbox Code Playgroud)

  • ```config.url = config.url +'?id = 123'; return config || $ q.when(config);```在访问```config.url```之后,什么会使```config```评估为false? (2认同)