AngularJS全球每一个修改请求的URL中的$ HTTP [英] AngularJS globally modify the URL of every request in $http

查看:116
本文介绍了AngularJS全球每一个修改请求的URL中的$ HTTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's set up a simple example:

$scope.whatDoesTheFoxSay = function(){
    $http.post("/backend/ancientMystery", {
...

我如何改变全球其中POST请求发送到网址是什么?实际上我想一个URL追加到每个HTTP请求。

How can I globally transform the URL where the post request is sent to? Practically I want to append an URL to every http request.

我曾尝试是,在应用程序初始化,设置在变量中包含的URL,但它不是我期待的 $ rootScope

What I have tried is, on application init, setting a variable in the $rootScope containing the url but it is not what I am looking for:

$scope.whatDoesTheFoxSay = function(){
    $http.post($rootScope.backendUrl+"/backend/hidingDeepInTheWoods", {
...

我是不是正确的假设,我应该看看 $ httpProvider.defaults.transformRequest ?任何人都可以给我提供一些基本的例子code?

Am I correct assuming that I should look into $httpProvider.defaults.transformRequest ? Can anyone provide me with some basic example code?

推荐答案

我在使用请求拦截与$ HTTP的另一种方法,将处理所有URL的在一个共同的地方。

I have another approach of using request interceptor with $http which will handle all the url's at one common place

<!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>

这篇关于AngularJS全球每一个修改请求的URL中的$ HTTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆