在尝试访问一个安全的Api时,我需要在我的angular http请求中发送头部数据
JavaScript代码:
$http.post('http://localhost/api/validate', user).success(function () {
$scope.reset();
$scope.activePath = $location.path('/');
如何在此请求中发送头数据?
在尝试访问一个安全的Api时,我需要在我的angular http请求中发送头部数据
JavaScript代码:
$http.post('http://localhost/api/validate', user).success(function () {
$scope.reset();
$scope.activePath = $location.path('/');
//store the header data in a variable
var headers = { 'Authorization': authToken };
//Add headers with in your request
$http.post('http://localhost/api/validate',user, { headers: headers } ).success(function()
对于身份验证,我发现这段代码很有用。假设令牌在成功登录后存储在 cookie 中,
.factory('authInterceptor', function ($q, $cookieStore) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if(response.status === 401) {
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})