最新版Angular调用checkSession接口subscribe始终触发error回调问题
问题解决方案
你的错误是token存储、传参逻辑错误,以及空值判断逻辑错误导致的,按以下步骤修复即可:
1. 修复登录成功后存储token的逻辑
你当前直接将整个响应对象序列化后存储,课程里是只取响应里的token字段存储,现在新版Angular的HttpClient会自动解析JSON响应,不需要调用.json()方法,修改onSubmit代码:
onSubmit() { this.loginService .sendCredential(this.credential.username, this.credential.password) .subscribe( res => { // 只存返回结果里的token字段,不要序列化整个响应对象 localStorage.setItem('xAuthToken', res.token); this.loggedIn = true; const encodedCredentials = btoa(this.credential.username + ':' + this.credential.password); localStorage.setItem('credentials', encodedCredentials); }, error => { // 用逗号分隔打印,不要字符串拼接,能看到完整错误信息 console.log("登录错误:", error); } ); }
2. 修复checkSession的请求头构造逻辑
你给x-auth-token多做了一次序列化,导致传过去的token多了一层引号,后端无法识别,修改checkSession代码:
checkSession() { const url = 'http://localhost:8181/checkSession'; const xToken = localStorage.getItem('xAuthToken'); const basicHeader = 'Basic ' + localStorage.getItem('credentials'); const headers = new HttpHeaders({ // 直接传token即可,不要JSON.stringify 'x-auth-token' : xToken, 'Authorization' : basicHeader }); return this.http.get(url, {headers: headers}); }
3. 修复ngOnInit的token存在性判断逻辑
你将getItem的返回值序列化后判断,当本地没有token时getItem返回null,序列化后得到字符串"null",这是真值会触发无效请求,修改代码:
ngOnInit() { // 直接判断原始值是否存在即可 const xToken = localStorage.getItem('xAuthToken'); if (xToken) { this.loginService.checkSession().subscribe( res => { console.log("会话有效") this.loggedIn = true; }, error => { // 逗号分隔打印错误对象,不要字符串拼接 console.log("会话校验错误:", error) this.loggedIn = false; } ); } }
额外调试说明
如果修改后还有问题,打开浏览器控制台的网络面板,查看checkSession请求的请求头里x-auth-token的值,和本地存储里的xAuthToken值、登录接口返回的token值对比,确认三者一致即可。
内容的提问来源于stack exchange,提问作者WannaBeDev
相关产品推荐
相关产品推荐

