Angular 5 在 http get 请求中正确传递标头 [英] Angular 5 pass headers properly in http get requests

查看:30
本文介绍了Angular 5 在 http get 请求中正确传递标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以最初我使用已弃用的 HttpModule 来处理我的 api 请求,但我现在使用的是 HttpClientModule 并且在正确传递标头时遇到问题.我有一个函数可以调用 api 来获取一些数据……这就是我最初使用 HttpModule 的功能

<块引用>

service.ts

export class userService {//使用HttpModule获取当前配置文件(){让 v = this.page_header();返回 this.http.get(this.userProfileUrl, {headers: headers}).承诺().then(response => response.json()).catch(this.handleError);};//使用HttpClientModule获取当前配置文件(){让 headers = new HttpHeaders();返回 this.http.get(this.userProfileUrl, {headers: headers}).承诺().then(response => response.json()).catch(this.handleError);};私人页面标题(){让数据 = localStorage.getItem('auth_token');让标题=新标题();让选择:请求选项;headers.append('授权', 'JWT' + 数据);opt = new RequestOptions({ headers: headers });返回选择;}}

<块引用>

component.ts

getStoreProfile() {//使用HttpModulethis.userSrv.getCurrentProfile().then(response => {localStorage.setItem('store', JSON.stringify(response));this.profile = JSON.parse(localStorage.getItem('store'));}).catch(err => this.error = err)//使用HttpClientModulethis.userSrv.getCurrentProfile().subscribe(res => {让数据 = res;localStorage.setItem('store', JSON.stringify(res));this.profile = JSON.parse(localStorage.getItem('store'));})

}所以最初这一切都与 HttpModule 一起工作,但现在使用 HttpClientModule 我得到错误

detail:"未提供身份验证凭据."

我如何使用 HttpClientModule 正确传递标头.

解决方案

详细信息:未提供身份验证凭据."

您遇到此问题是因为您的标题为空.

使用 httpOptions 对象发送标头
在新的 HttpClientModule 中,JSON 是假定的默认值,不再需要使用 res.json()
推荐使用 observables 而不是 promises.通过转换为承诺,您将失去取消请求的能力和链接 RxJS 操作符的能力.

 getCurrentProfile():Observable{让数据 = localStorage.getItem('auth_token');const httpOptions = {标头:新的 HttpHeaders({'内容类型':'应用程序/json','授权':''JWT'+数据'})};返回 this.http.get(this.userProfileUrl, httpOptions).catch(this.handleError);};

so initially i was using the deprecated HttpModule for my api requests but i'm using the HttpClientModule now and having issues with passing headers correctly. i've got a function that calls api to get some data...this is what i had initially with HttpModule

service.ts

export class userService {
  //using HttpModule
  getCurrentProfile() {
    let v = this.page_header();
    return this.http.get(this.userProfileUrl, {headers: headers})
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  };

  //using HttpClientModule
  getCurrentProfile() {
    let headers = new HttpHeaders();
    return this.http.get(this.userProfileUrl, {headers: headers})
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  };

  private page_header() {
    let data = localStorage.getItem('auth_token');
    let headers = new Headers();
    let opt: RequestOptions;
    headers.append('Authorization', 'JWT ' + data);
    opt = new RequestOptions({ headers: headers });
    return opt;
  }
}

component.ts

getStoreProfile() {
 //using HttpModule
 this.userSrv.getCurrentProfile().then(response => {
   localStorage.setItem('store', JSON.stringify(response));
   this.profile = JSON.parse(localStorage.getItem('store'));
 }).catch(err => this.error = err)

 //using HttpClientModule
 this.userSrv.getCurrentProfile().subscribe(res => {
  let data = res;
  localStorage.setItem('store', JSON.stringify(res));
  this.profile = JSON.parse(localStorage.getItem('store'));
})

} So initailly it all worked with HttpModule but now with HttpClientModule i get errro

detail:"Authentication credentials were not provided."

How am i to pass headers correctly using HttpClientModule.

解决方案

detail:"Authentication credentials were not provided."

You are getting this issue because your header is empty.

use httpOptions object to send header
In new HttpClientModule JSON is an assumed default and no longer needs to be explicitly parsed using res.json()
it's recommended to use observables over promises. By converting to a promise you will lose the ability to cancel a request and the ability to chain RxJS operators.

 getCurrentProfile():Observable<any> {
    let data = localStorage.getItem('auth_token');
      const httpOptions = {
                headers: new HttpHeaders({
                    'Content-Type':  'application/json',
                        'Authorization': ' 'JWT ' + data'
         })
    };

        return this.http.get(this.userProfileUrl, httpOptions)
         .catch(this.handleError);
      };

这篇关于Angular 5 在 http get 请求中正确传递标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆