请求使用Postman但使用Angular返回401

问题描述 投票:0回答:1

这是我的角度方法

getGiftList(url: string){
let q = this.baseUrl + url;
let headers = new HttpHeaders();
let authToken = 'Bearer ' + this.authService.currentUser.token;

console.log(q); //Log the url ...
console.log(authToken); Log the token ...

headers.set('Authorization', authToken)

return this.http.get(q, {
  observe: 'response' 
  ,headers: headers
})

}

这是Asp.net的核心方法

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class GiftController : Controller
{
    [HttpGet("api/giftsByGiver/{email}")]        
    public IActionResult getGiftBasicRecordsByGiver(string email, int cpg = 1)
    {
       //
    }
}

当我从我的角度代码发出请求时,我得到一个401错误。但是,当我复制/删除我记录到Postman并运行的相同值时,我得到了正确的结果。

我错过了什么吗?

谢谢你的帮助

angular .net-core bearer-token
1个回答
4
投票

HttpHeaders是不可变的。调用set()不会改变它。它返回一个新的HttpHeaders实例。所以你需要

headers = headers.set('Authorization', authToken);

或者更简单,如果您更改说明的顺序:

const authToken = 'Bearer ' + this.authService.currentUser.token;
const headers = new HttpHeaders().set('Authorization', authToken);

您应该验证您的假设:只需打开浏览器开发工具的网络面板,然后检查您发送的内容是否是您认为发送的内容。

© www.soinside.com 2019 - 2024. All rights reserved.