Angular httpClient标头

时间:2018-03-15 11:36:50

标签: angular angular-httpclient

以下是我获取身份验证令牌的HTTP帖子请求,标头未设置,在Chrome中我没有看到请求标题下的标题。

enter image description here

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

我也试过启用“CORS”仍然是同样的问题。

尝试了所有评论选项。

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');
    }
    );

2 个答案:

答案 0 :(得分:1)

您应该使用here来实现此目的,一旦配置了它,它将自动为每个http请求的标头添加信息,您不必为每个http请求手动添加标头。

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

我希望这会有所帮助。

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"));
  }
}

我还建议您阅读HttpInterceptor文章,因为这会让您对此有更深入的了解。

答案 1 :(得分:0)

以下是我如何使用http.service.ts设置HttpClient的示例。这对我来说完美无瑕,我可以看到我的标题是相应的。

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { RequestOptions } from '../models/http.models';

@Injectable()
export class HttpService {
  domain: string = 'https://example-production.systems/';
  options: RequestOptions = {
    withCredentials: true,
    headers: new HttpHeaders({ 'X-CSRFToken': 'example-token' }),
  };

  constructor(
    public httpClient: HttpClient,
  ) {}

  post = (path: string, payload: any, query?: string): Observable<any> =>
    this.httpClient.post(`${this.domain}/${path}/${query}`, payload, this.options)
}

如果你是好奇 - 我的RequestOptions界面如下所示:

export interface RequestOptions {
  headers: HttpHeaders;
  withCredentials: boolean;
}

我在接受的HTTPClient选项列表中构建了此接口,可以在各种HTTPClient client.d.ts方法中找到。例如 - 接受的.post()选项如下:

post(url: string, body: any | null, options?: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<Object>;