2016-06-09 1 views
1

Я использую angularjs, В backend я проверяю каждый api аутентифицированный. В каждом запросе должен быть указан параметр access_token.Angularjs + interceptors + добавить параметры запроса только для http-запроса (не html, js, css-файлов)

$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'); 

Я использую этот код. Его работа хорошая, но я видел в средствах разработки (Network) файлы 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 за то, что есть у префиксов апи

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. 

я ожидаю только лишь запрос бэкенд апи. Также я не ожидаю, что каждый серийный запрос http добавит параметр.

Его можно добавить общее одно место в config?

ответ

3

Вы можете проверить 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'); 
Смежные вопросы