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

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

问题描述

让我们建立一个简单的例子:

Let's set up a simple example:

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

如何全局转换 post 请求发送到的 URL?本质上,我想为每个 http 请求添加一个 URL.

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

我所尝试的是在应用程序启动时在包含 url 的 $rootScope 中设置一个变量.但这不是我想要的代码:

What I have tried is setting a variable in the $rootScope containing the url when the application starts. But this is not what I want my code to look like:

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

假设我应该查看 $httpProvider.defaults.transformRequest 是否正确?谁能提供一些基本的示例代码?

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 全局修改 $http 中每个请求的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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