您是否检查过令牌实际上已添加到您的请求中?
例如,您可以使用 Chrome 开发人员工具来执行此操作。
就我个人而言,我更喜欢使用 $httpprovider.interceptor,如下所述:
angularjs $httpProvider 拦截器文档 https://stackoverflow.com/questions/26171986/angularjs-httpprovider-interceptor-documentation
这可确保令牌始终出现在任何调用中。
如果您要访问多个 API,您应该考虑添加如下内容:
$httpProvider.interceptors.push(['$q', '$location', '$log', 'loginService', 'restHelperService',
function ($q, $location, $log, loginService, restHelperService) {
return {
request: function (config) {
// check if the request comes with an url
if (config.url) {
// check that the call is to the REST api, if yes add token
if (restHelperService.isRestCall(config.url)) {
// add auth header or revert to login
if (loginService.userIsLoggedIn()) {
config.headers = config.headers || {};
config.headers.Authorization = 'Token ' + loginService.getToken().token;
} else {
$location.path('/login');
}
}
}
return config;
},
responseError: function (response) {
if (response.status === 401 || response.status === 403) {
// clear auth token if the REST call failed with the current token
if (response.config && response.config.url && restHelperService.isRestCall(response.config.url)) {
$log.debug(" restCall failed due to bad credentials, resetting credentials");
loginService.resetCredentials();
$location.path('/login');
}
}
return $q.reject(response);
}
};
}]);
}])
这可以避免当您开始将令牌添加到不需要它们的 API 调用时出现的问题。此外,该代码还确保如果凭据无效,用户将自动重定向到登录页面。
例如,我正在使用两项附加服务。管理令牌的 loginService 和管理 REST 框架 url 的restHelperService。
我建议您执行相同的操作,否则将很难从控制器外部访问凭据。