Angularjs + перехватчики + добавить параметры запроса только для http-запроса (не файлы html, js, css)

Я использую 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).

Мне нравится отправлять access_token для того, что имеет префикс API

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-запрос будет добавлять параметр.

Можно ли добавить общее место в конфиг?


person RSKMR    schedule 09.06.2016    source источник


Ответы (1)


Вы можете проверить URL:

$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');
person Anton Kirzyk    schedule 09.06.2016