首页 > 解决方案 > 将令牌作为 http 调用插入标头

问题描述

我有代码:

const parameters = 'Account/GetDoctorDetails?userId=' + 63;
this.http.get(`${webserviceUrlLocalHost}` + parameters)
.subscribe(response => {
  console.log('response.json()');
  console.log(response.json());

我想在这个调用中插入一个令牌到 GET webapi 调用中,所以我将我的代码更改为:

const headers = new Headers({ 'Authorization': `Bearer ` + token });
const options2 = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:55803/Account/GetDoctorDetails?userId=63', options2)
    .subscribe( response => console.log(response.json())); */

但是该函数永远不会被调用;知道为什么它不起作用吗?

标签: angulartoken

解决方案


从文档中尝试new HttpHeaders代替new RequestOptions已弃用):

添加标题,如:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

所以你options2应该是:

const options2 = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': `Bearer ` + token
  })
};

推荐阅读