【问题标题】:How to get absolute URL in angular HTTP Interceptor?如何在角度 HTTP 拦截器中获取绝对 URL?
【发布时间】:2018-09-05 21:50:29
【问题描述】:

在我们的应用程序中,对于每个请求,前端都会对 url + 数据进行哈希处理并将它们发送到服务器。然后服务器验证查询参数以及数据没有被篡改。但是,在httpinterceptor中,我只能查看config.url和config.params。没有办法获得绝对网址,所以我不能直接对它进行哈希处理。我该怎么做呢?我尝试了一些类似

的东西
var url;
var params;
for (var i = 0; i < config.params.length; i++){
    params+=config.params[i].name+'='+config.params[i].value;
}
url = config.url+'?'+params;

但这不起作用,因为我似乎无法以这种方式访问​​参数。另外,如何确定参数与请求 URL 的顺序相同?显然,如果它甚至有 1 个字符不同,哈希就不会是正确的。

【问题讨论】:

  • 为什么不window.location.href
  • 为什么获取绝对网址这么难?您知道应用程序中的基础是什么,并且可以轻松地将其设置为常量
  • @charlietfl 使用 config.url 获取基本 url 很好,但我也需要查询字符串。
  • @AvraamMavridis,window.location.href 仅对我所在页面的 url 有帮助。它无法帮助我获取 API 调用的 URL
  • 我非常需要这个。我也发布了一个单独的问题。 link

标签: angularjs angular-http-interceptors


【解决方案1】:

这可以通过添加过滤器并推送到拦截器来实现

angular.module("app").config(['$httpProvider', function ($httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
            $httpProvider.interceptors.push('myHttpInterceptor');
        }
        else {
        }
        $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
    }
]);

并编写过滤器来拦截请求和响应及其错误

angular.module('app').factory('myHttpInterceptor', function($q) {
    return {
      // optional method
      'request': function(config) {

        return config;
      },

      // optional method
     'requestError': function(rejection) {
        // do something on error
        return $q.reject(rejection);
      },



      // optional method
      'response': function(response) {
        // do something on success
        return response;
      },

      // optional method
     'responseError': function(rejection) {
        // do something on error
        return $q.reject(rejection);
      }
    };
  });

在请求中配置参数将包含 URL 以及参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2018-07-25
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多