首页 > 解决方案 > 在使用 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。

标签: angularapirestionic-framework

解决方案


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)
}, 

推荐阅读