Angular httpClient 标头 [英] Angular httpClient headers

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

问题描述

下面是我的 HTTP post 请求以获取身份验证令牌,标头未设置,在 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天全站免登陆