【问题标题】:Angularjs + interceptors + add query parameters for only http request( not html,js,css files)Angularjs + 拦截器 + 仅为 http 请求添加查询参数(不是 html、js、css 文件)
【发布时间】:2016-06-09 15:08:25
【问题描述】:

我正在使用 angularjs,在后端我检查每个经过身份验证的 api。 每个请求都应该检查参数access_token。

$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
    return {
        request : function(config) {
            config.params = config.params || {};
            if ($localStorage.access_token) {
                config.params.access_token = $localStorage.access_token;
            }
            return config || $q.when(config);
        },
    };
});

// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor'); 

我使用此代码。它工作得很好,但我在开发工具(网络)中看到 html、css、js 文件也添加了参数。 喜欢。

http://localhost/webapp/views/template/left-menu.html?access_token=xxxxxxxxxxxxxxxxx
http://localhost/webapp/css/index.css?access_token=xxxxxxxxxxxxxxxxx

但我不喜欢将 access_token 发送到所有 http 请求(html、css、js)。

我喜欢发送带有前缀 api 的 access_token

http://localhost:9090/api/user/get?access_token=xxxxxxxxxxxxxxxxxxxxxx

//I think the solution is find the http url and grep the text api, if found means add the parameter. Don't konw this is good approach.

Please me the good approach.

我只希望后端 api 请求。 另外我不希望每个服务 http 请求都添加参数。

是否可以在config中添加一个common的地方?

【问题讨论】:

    标签: angularjs http factory interceptor


    【解决方案1】:

    您可以查看网址:

    $provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
    return {
        request : function(config) {
            var apiPattern = /\/api\//;
    
            config.params = config.params || {};
    
            if ($localStorage.access_token && apiPattern.test(config.url)) {
                config.params.access_token = $localStorage.access_token;
            }
            return config || $q.when(config);
        }
      };
    });
    // Add the interceptor to the $httpProvider.
    
    $httpProvider.interceptors.push('MyHttpInterceptor');
    

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2014-05-26
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多