Ustawianie nagłówków HTTP w aplikacji AngularJS
Czy istnieje sposób, aby ustawić $httpProvider
nagłówki poza angular.module('myApp', []).config()
?
Otrzymuję Auth-Token z serwera po zalogowaniu użytkownika i muszę dodać go jako nagłówek HTTP do wszystkich następujących żądań.
46
3 answers
Możesz użyć domyślnych nagłówków dla angular 1.0.x :
$http.defaults.headers.common['Authentication'] = 'authentication';
Lub Prośba o kątowe 1.1.x+:
myapp.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
// use this to destroying other existing headers
config.headers = {'Authentication':'authentication'}
// use this to prevent destroying other existing headers
// config.headers['Authorization'] = 'authentication';
return config;
}
};
});
myapp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
Ponieważ fabryki/usługi są singletonami, działa to tak długo, jak nie trzeba dynamicznie zmieniać wartości "uwierzytelniania" po utworzeniu instancji usługi.
66
Author: Leonardo Zanivan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 00:34:20
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 00:34:20
$http.defaults.headers.common['Auth-Token'] = 'token';
Wydaje się headers()
normalizuje nazwy kluczy.
39
Author: lucassp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-06 14:49:22
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-06 14:49:22
Dodanie do powyższych odpowiedzi @Guria i @Panga
config.headers['X-Access-Token'] = $window.sessionStorage.token;
Można użyć x-access-token w nagłówku jako JWT (jsonwebtoken). Zapisuję JWT w pamięci sesji, gdy użytkownik uwierzytelnia się po raz pierwszy.
1
Author: Pranjal Singi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-14 10:40:51
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-14 10:40:51