是的,当我尝试将AuthInterceptor包含在index.html中时,我遇到了奇怪的TypeError。当我尝试加载显示我的登录页面的localhost:8080 /#/ login时,出现此错误。不包含在这里,因为它不相关。当我删除index.html中指向AuthInterceptor的链接时,我的登录页面成功呈现。
js / app / services / AuthInterceptor.js
function AuthInterceptor() {
this.request = function(config) {
config.headers = config.headers || {};
return config;
};
this.response = function(response) {
if (response.status === 401) {
alert('STATUS 401!');
return response;
}
};
}
angular
.module('app')
.service('AuthInterceptor', AuthInterceptor)
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
index.html
<!doctype html>
<html>
<head>
<script src="js/app/angular.js"></script>
<script src="js/app/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.css">
<script src="js/app/app.js"></script>
<script src="js/app/controllers/LoginController.js"></script>
<script src="js/app/controllers/MainController.js"></script>
<script src="js/app/services/AuthInterceptor.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Angular Application</title>
</head>
<body ng-app="app">
<div ui-view></div>
</body>
</html>
最佳答案
问题在于,在拦截器中,只有在遇到401错误时才传递响应,拦截器的目标是在请求之前或之后运行代码,并传递错误/响应。
您应该始终如一地传递它们。记录到控制台的错误仅表示您在应用程序另一部分中发出的请求失败,因为未传递响应时,未定义promises的.then()中的data参数,并且会引发错误。
this.response = function(response) {
if (response.status === 401) {
alert('STATUS 401!');
return response;
}
return response; // Always return response
};
希望能帮助到你
关于javascript - 收到TypeError:尝试包含我用AngularJS制作的AuthInterceptor服务时,无法读取未定义的属性“data”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38044324/