You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular HTTP GET请求的请求头中插入认证Token?

在GET请求中添加Token请求头的完整实现

嘿,我来帮你把Token正确插入到WebAPI请求的请求头里~你已经写好了请求头和配置项的基础代码,只需要把它们和原来的GET请求整合起来就行,下面是完整的可运行代码:

// 假设token已经通过合适的方式获取到(比如从localStorage、登录接口返回等)
const token = '你的实际Token值';

// 构造请求头,添加Authorization的Bearer Token
const headers = new Headers({ 'Authorization': `Bearer ${token}` }); 
const options2 = new RequestOptions({ headers: headers }); 

// 构造请求参数
const parameters = 'Account/GetDoctorDetails?userId=' + 63; 
// 把options2作为第二个参数传入get方法,请求头就会被携带上
this.http.get(`${webserviceUrlLocalHost}` + parameters, options2) 
.subscribe(response => { 
    console.log('response.json()'); 
    console.log(response.json()); 
});

关键说明:

  • 一定要确保token变量已经被正确赋值(比如从登录接口返回后存在localStorage中,用localStorage.getItem('token')获取),不然请求头里的Token会是无效值
  • 你之前的代码已经正确构造了包含Token的请求头,核心就是把options2作为第二个参数传递给http.get()方法,这样Angular就会把这个配置里的请求头附加到请求中
  • 如果是Angular 4.3+版本,官方推荐使用HttpClient替代旧的Http服务,对应的请求头构造会更简洁:
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    this.httpClient.get(`${webserviceUrlLocalHost}${parameters}`, { headers })
      .subscribe(response => console.log(response));
    

内容的提问来源于stack exchange,提问作者dtjmsy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:55:23