首页 文章

Angular httpClient标头

提问于
浏览
0

下面是我获取auth令牌的HTTP post请求,标头未设置,在chrome中我没有看到请求标头下的标头 .

enter image description here

我还观察到,如果我只添加内容类型 Headers ,我可以看到请求中发送的 Headers 和正文,如果我添加授权 Headers 然后在请求中没有发送 Headers 或正文,我看到对预检的响应已经无效的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 回答

  • 1

    你应该做的是使用HttpInterceptor为此目的,一旦配置它,它将自动为每个http请求的 Headers 添加信息,你不必为每个http请求手动添加 Headers .

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

    我希望这有帮助 .

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

    我还建议您阅读this文章,因为这将为您提供更多的见解 .

  • 0

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

    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>;
    

相关问题