无法将自定义标头添加到HttpService(Angular v4)

时间:2017-05-16 14:06:35

标签: angular dropwizard

我试图通过扩展默认的Http类并覆盖request()方法来追加特定的授权自定义标头,从而在angular(v4)应用程序中为请求添加自定义标头。该课程如下:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptionsArgs, Request, Response, ConnectionBackend, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthToken } from '../authentication/auth-token';


@Injectable()
export class ZHttpService extends Http {

  private HEADER_AUTHORIZATION: string = 'X-Z-AUTHORIZATION';

  constructor(protected backend: ConnectionBackend, protected defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  private setCustomHeaders(options?: RequestOptionsArgs):RequestOptionsArgs{
    if(!options) {
      options = new RequestOptions({});
    }

    let authTokenJSON = localStorage.getItem("z-auth-token");

    if(authTokenJSON) {
      if (!options.headers) {
        options.headers = new Headers();
      }

      let authToken: AuthToken = JSON.parse(authTokenJSON);
      options.headers.append(this.HEADER_AUTHORIZATION, `${authToken.token}`);
    }
    return options;
  }

  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    options = this.setCustomHeaders(options);
    return super.request(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError (self: ZHttpService) {
    return (res: Response) => {
      console.log(res);
      if (res.status === 401 || res.status === 403) {
        console.log(res);
      }
      return Observable.throw(res);
    };
  }

  public isAuthenticated() {
    return localStorage.getItem("z-auth-token") != null;
  }
}

使用此自定义http服务的类只执行以下操作(在此实例中):

...
constructor (private http: ZHttpService) {}

  getAccount(): Observable<Account> {
    return this.http.get(this.accountUrl)
      .map(this.parseAccount)
      .catch(this.handleError); 
  }
...

正在成功检索令牌并且正在执行此代码。但是,在传出请求中,不存在自定义标头。

CORS在服务器端配置(DropWizard),如下所示:

// Cross Origin Policy Configuration
final FilterRegistration.Dynamic corsFilterConfig = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
corsFilterConfig.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
corsFilterConfig.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
corsFilterConfig.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
corsFilterConfig.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD");

// Cors URL Mapping
corsFilterConfig.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "*");

// Restriction to Permit Unauthenticated Preflight Responses
corsFilterConfig.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, Boolean.FALSE.toString());

当从角度应用程序发出请求时,会出现以下标题。

Request Headers

正在使用的Angular版本是最新的,这里是ng --version输出。

@angular/cli: 1.0.3
node: 6.10.2
os: win32 x64
@angular/animations: 4.1.2
@angular/animations/browser: undefined
@angular/common: 4.1.2
@angular/compiler: 4.1.2
@angular/core: 4.1.2
@angular/forms: 4.1.2
@angular/http: 4.1.2
@angular/material: 2.0.0-beta.5
@angular/platform-browser: 4.1.2
@angular/platform-browser-dynamic: 4.1.2
@angular/platform-browser/animations: undefined
@angular/router: 4.1.2
@angular/cli: 1.0.3
@angular/compiler-cli: 4.1.2

我有不正确的做法吗?这是Angular的错误吗?我的DropWizard配置不正确吗?

应该注意的是,如果我使用PostMan发出相同的请求(在邮递员中添加标题),该服务将按预期工作。

谢谢!

1 个答案:

答案 0 :(得分:2)

您在setCustomHeaders方法中使用request。但是,如果从超类中调用get,超类将使用自己的request代替。因此,您还需要覆盖get方法。