我在AngularJS中使用我的后端api进行了基于令牌的身份验证的以下代码:
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);
这会将“Authorization”标头设置为我的令牌。
如何修改我的代码以使用URL参数(名为“access_token”)而不是标题?
答案 0 :(得分:2)
你需要使用 config 对象的 params - {Object。} 参数:
params – {Object.<string|Object>}
- 要转到的字符串或对象的映射?url后的key1 = value1&amp; key2 = value2。如果该值不是字符串,则它将是JSONified。
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
//config.headers = config.headers || {};
config.params = config.params || {};
if ($localStorage.token) {
config.params.access_token = $localStorage.token;
//config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);