angular - 在使用 HttpHeaders 发送 POST 请求时在 Ionic 应用程序中获取未经身份验证的 401
问题描述
我正在发送带有标头信息的 POST 请求。
如果我使用注销功能,一切正常,后端返回 200 成功状态。如果我使用函数 updateName,我会不断收到 401 Unauthenticated。
在这两种情况下,我都将相同的访问令牌发送到后端。
有什么见解或我缺少的东西吗?
users.service.ts
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Authorization': 'Bearer ' + localStorage.getItem("access_token")
}),
observe : 'response' as 'response'
};
updateName(data) {
this.http.post(environment.getBaseAddress() + 'users/updateName', data, this.httpOptions).subscribe((data) => {
this.router.navigateByUrl('current-location');
});
}
logout(){
this.http.get(environment.getBaseAddress() + 'logout', this.httpOptions).subscribe((data) => {
localStorage.removeItem("authToken");
localStorage.removeItem("access_token");
if (localStorage.getItem("access_token") === null) {
console.log("access is now null" + localStorage.getItem("access_token"));
console.log("auth is now null" + localStorage.getItem("access_token"))
this.router.navigateByUrl("");
}
else console.log("error during removal")
});
}
错误显示
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"OK","url":"https://myserverinfo.com/api/users/updateName","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://myserverinfo.com/api/users/updateName: 401
不确定它是否有帮助,但注销是 GET,而 updateName 是 POST。
解决方案
The issue was my this.httpOptions in the requests. Inserting the header details in the request itself. I rewrote the functions this way:
this.http.post(environment.getBaseAddress() + 'users/updateName', data, { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem("access_token")
})}).subscribe((data) => {
this.router.navigateByUrl('current-location');
console.log(data)
},
推荐阅读
- angular - 如何在 FormArray 中添加 Angular Material 自动完成
- javascript - 移动长按增量位置
- php - PHP:基本数组切片情况
- hadoop - 无法从远程主机访问 Hue UI
- php - 使用 If 语句更改数组输出
- rx-java - RxJava - 我可以绕过 onSuccess 并且只有 onError 选项吗?
- java - 实施 onClick 子菜单以开始新活动
- ruby-on-rails - Rails - 通过表插入 has_many
- android - Spring for Android:请求授权标头(非基本)
- r - 获取R中两个字符串之间的字符匹配长度