Angular httpClient标头 [英] Angular httpClient headers

查看:83
本文介绍了Angular httpClient标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我获取身份验证令牌的HTTP发布请求,没有设置标头,在chrome中,我没有在请求标头下看到标头.

Below is my HTTP post request to get the auth token, the headers are not getting set, in chrome I don't see the headers under request headers.

我还观察到,如果仅添加内容类型标头,则可以看到请求中发送的标头和正文,如果添加授权标头,则在请求中不发送标头或正文,我可以看到 对预检的响应具有无效的HTTP状态代码401.控制台上的错误.

What I also observed is, if I add only the content-type header I can see the header and body being sent in the request, if I add authorization header then no header or body being sent in the request and I see Response to preflight has invalid HTTP status code 401. error on console.

我还尝试启用"CORS"仍然是同样的问题.

I also tried enabling "CORS" still the same issue.

尝试了所有评论的选项.

have tried all the commented options.

let headers = new HttpHeaders({ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'authorization': 'Basic ' + btoa("infoarchive.custom:mysecret") });

//headers  = headers.append("content-type","application/x-www-form-urlencoded");
//headers  = headers.append("authorization","Basic " + btoa("infoarchive.custom:mysecret"));
//headers = headers.set("Access-Control-Expose-Headers", "Authorization")
//headers = headers.set(Content-Type', 'application/x-www-form-urlencoded')
//headers = headers.set('Authorization', 'Basic aW5mb2FyY2hpdmUuY3VzdG9tOm15c2VjcmV0');      
console.log(headers)
const body = JSON.stringify({
    client_id: 'infoarchive.custom',
    username: userName,
    password: password,
    grant_type: 'password',
    scope: 'search'
});
return this.http.post('http://localhost:8080/oauth/token', body, { headers: headers })
    .map(
    (response: Response) => {
        const data = response.json();
        console.log("data:" + data)
        //  this.saveJwt(data.json().id_token);             
    }
    )
    .catch(
    (error: Response) => {
        console.log(error.status)
        return Observable.throw('Something went wrong');
    }
    );

推荐答案

您应该做的是使用 HttpInterceptor 为此目的,配置完成后,它将为每个http请求自动向您的标头添加信息,而您不必为每个http请求手动添加标头.

What you should do is use HttpInterceptor for this purpose and once this is configured it will automatically add information to your header for every http request and you will not have to manually add headers for every http request.

以下是如何从存储中获取 user 对象并使用其authentication_token并将其作为标头的一部分发送的示例.

Following is an example of how I am getting a user object from the storage and using its authentication_token and sending it as a part of a header.

我希望这会有所帮助.

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs";
import { Storage } from "@ionic/storage";
import "rxjs/add/operator/mergeMap";

@Injectable()
export class AuthInterceptorProvider implements HttpInterceptor {
  constructor(private storage: Storage) {
    console.log("Hello AuthInterceptorProvider Provider");
  }

  intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {

    return this.getUser().mergeMap(user => {
      if (user) {
        // clone and modify the request
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${user.authentication_token}`
          }
        });
      }

      return next.handle(request);
    });
  }

  getUser(): Observable<any> {
    return Observable.fromPromise(this.storage.get("user"));
  }
}

我还将建议您阅读

I will also recommend you to read this article as this will give you more insight on this.

这篇关于Angular httpClient标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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