IT

각도 - 모든 요청에 대한 헤더 설정

itgroup 2023. 5. 13. 09:27
반응형

각도 - 모든 요청에 대한 헤더 설정

사용자가 로그인한 후 모든 후속 요청에 대해 일부 인증 헤더를 설정해야 합니다.


특정 요청에 대한 헤더를 설정하려면,

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);

// HTTP POST using these headers
this.http.post(url, data, {
  headers: headers
})
// do something with the response

언급

그러나 이러한 방식으로 모든 요청에 대해 요청 헤더를 수동으로 설정할 수는 없습니다.

사용자가 로그인한 후 헤더 집합을 설정하고 로그아웃 시 해당 헤더를 제거하려면 어떻게 해야 합니까?

답하기 위해, 을 포장하는 서비스를 할 수 합니다.HttpAngular의 객체입니다.아래에 설명된 것과 같은 것입니다.

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {

  constructor(private http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('username:password')); 
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, {
      headers: headers
    });
  }

  post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, {
      headers: headers
    });
  }
}

주사를 에.Http할 수 (신이이것주수물있체당는할입을▁you▁(▁object물체당▁inject▁this있▁(▁one)HttpClient).

import { HttpClient } from './http-client';

export class MyComponent {
  // Notice we inject "our" HttpClient here, naming it Http so it's easier
  constructor(http: HttpClient) {
    this.http = httpClient;
  }

  handleSomething() {
    this.http.post(url, data).subscribe(result => {
        // console.log( result );
    });
  }
}

또한 여러 공급자를 사용하여 다음과 같은 작업을 수행할 수 있다고 생각합니다.Http.Http1... 다음 링크 참조: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html

HTTP 인터셉트는 이제 새로운 From을 통해 사용할 수 있습니다.@angular/common/httpAngular 4.3.x 버전 이후.

이제 모든 요청에 대해 머리글을 추가하는 것은 매우 간단합니다.

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({ headers: req.headers.append('Authorization', 'Bearer 123') });

    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
  }
}

불변성의 원칙이 있습니다. 이것이 요청을 복제한 후 새로운 것을 설정해야 하는 이유입니다.

헤더 편집은 매우 일반적인 작업이므로 요청을 복제하는 동안 다음과 같은 바로 가기가 있습니다.

const clonedRequest = req.clone({ setHeaders: { Authorization: 'Bearer 123' } });

인셉터를후다사합등니다야록해용여하음을 .HTTP_INTERCEPTORS제공하다.

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AddHeaderInterceptor,
    multi: true,
  }],
})
export class AppModule {}

BaseRequestOptions이 시나리오에서 큰 도움이 될 수 있습니다.다음 코드를 확인하십시오.

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http';

import {AppCmp} from './components/app/app';


class MyRequestOptions extends BaseRequestOptions {
  constructor () {
    super();
    this.headers.append('My-Custom-Header','MyCustomHeaderValue');
  }
} 

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(RequestOptions, { useClass: MyRequestOptions })
]);

여기에는 모든 통화에 'My-Custom-Header'가 포함되어야 합니다.

업데이트:

위의 코드 대신 원하는 시간에 헤더를 변경할 수 있도록 다음 코드를 사용하여 새 헤더를 추가할 수도 있습니다.

this.http._defaultOptions.headers.append('Authorization', 'token');

삭제할 수 있습니다.

this.http._defaultOptions.headers.delete('Authorization');

또한 값을 설정하는 데 사용할 수 있는 다른 기능이 있습니다.

this.http._defaultOptions.headers.set('Authorization', 'token');

위 솔루션은 여전히 유형 스크립트 컨텍스트에서 완전히 유효하지 않습니다._기본값머리글은 보호되며 이렇게 사용하면 안 됩니다.저는 빠른 수정을 위해 위의 솔루션을 추천하고 싶지만, 장기적으로 인증도 처리하는 http 호출 주위에 독자적인 래퍼를 작성하는 것이 더 좋습니다.auth0에서 더 좋고 깨끗한 다음 예를 들어 보겠습니다.

https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts

업데이트 - 2018년 6월 저는 많은 사람들이 이 솔루션에 찬성하는 것을 보지만 그렇지 않은 것이 좋습니다.헤더를 전체적으로 추가하면 앱에서 나가는 모든 API 호출에 인증 토큰이 전송됩니다.따라서 인터콤이나 젠데스크와 같은 타사 플러그인으로 가는 API 호출은 사용자의 인증 헤더도 전달합니다.이로 인해 큰 보안 결함이 발생할 수 있습니다.따라서 전체적으로 인터셉트카를 사용하되 발신 호출이 서버의 api 끝점을 향하고 있는지 수동으로 확인한 다음 인증 헤더를 첨부합니다.

비록 내가 그것에 매우 늦게 대답하지만 다른 사람에게 도움이 될 수도 있습니다.다음 시간에 모든 요청에 헤더를 주입하려면 다음과 같이 하십시오.@NgModule를 사용하면 다음 작업을 수행할 수 있습니다.

(Angular 2.0.1에서 테스트했습니다.)

/**
 * Extending BaseRequestOptions to inject common headers to all requests.
 */
class CustomRequestOptions extends BaseRequestOptions {
    constructor() {
        super();
        this.headers.append('Authorization', 'my-token');
        this.headers.append('foo', 'bar');
    }
}

지은금에서@NgModule다음을 수행합니다.

@NgModule({
    declarations: [FooComponent],
    imports     : [

        // Angular modules
        BrowserModule,
        HttpModule,         // This is required

        /* other modules */
    ],
    providers   : [
        {provide: LocationStrategy, useClass: HashLocationStrategy},
        // This is the main part. We are telling Angular to provide an instance of
        // CustomRequestOptions whenever someone injects RequestOptions
        {provide: RequestOptions, useClass: CustomRequestOptions}
    ],
    bootstrap   : [AppComponent]
})

Angular 2.1.2저는 각진 Http를 확장함으로써 이것에 접근했습니다.

import {Injectable} from "@angular/core";
import {Http, Headers, RequestOptionsArgs, Request, Response, ConnectionBackend, RequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HttpClient extends Http {

  constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {

    super(_backend, _defaultOptions);
  }

  _setCustomHeaders(options?: RequestOptionsArgs):RequestOptionsArgs{
    if(!options) {
      options = new RequestOptions({});
    }
    if(localStorage.getItem("id_token")) {

      if (!options.headers) {

        options.headers = new Headers();


      }
      options.headers.set("Authorization", localStorage.getItem("id_token"))
    }
    return options;
  }


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

앱 공급자에서 사용자 지정 팩토리를 사용하여 'Http'를 제공할 수 있었습니다.

import { RequestOptions, Http, XHRBackend} from '@angular/http';
import {HttpClient} from './httpClient';
import { RequestOptions, Http, XHRBackend} from '@angular/http';
import {HttpClient} from './httpClient';//above snippet

function httpClientFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
  return new HttpClient(xhrBackend, requestOptions);
}

@NgModule({
  imports:[
    FormsModule,
    BrowserModule,
  ],
  declarations: APP_DECLARATIONS,
  bootstrap:[AppComponent],
  providers:[
     { provide: Http, useFactory: httpClientFactory, deps: [XHRBackend, RequestOptions]}
  ],
})
export class AppModule {
  constructor(){

  }
}

할 필요가 " " " " " " " " " " " " " 을 사용할 수 .http내 지원서 전체에 걸쳐 정상적으로.

Angular 5 이상의 경우 HttpInterceptor를 사용하여 요청 및 응답 작업을 일반화할 수 있습니다.이를 통해 중복을 방지할 수 있습니다.

공통 헤더

응답 유형 지정

요청 쿼리 중

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  requestCounter: number = 0;
  constructor() {
  }

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

    request = request.clone({
      responseType: 'json',
      setHeaders: {
        Authorization: `Bearer token_value`,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    });

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        // do stuff with response error if you want
      }
    });
  }
}

이 AuthHttp를 사용할 수 있습니다.HttpIntercepters에 대한 공급자로서의 Interceptor 클래스:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true
    }
  ],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

2 Angular 를 .Http를 합니다.constructor그리고.request메서드가 사용자 지정 Http 클래스에 있습니다.아래 예제는 다음을 추가합니다.Authorization모든 http 요청의 헤더입니다.

import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class HttpService extends Http {

  constructor (backend: XHRBackend, options: RequestOptions) {
    let token = localStorage.getItem('auth_token'); // your custom token getter function here
    options.headers.set('Authorization', `Bearer ${token}`);
    super(backend, options);
  }

  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    let token = localStorage.getItem('auth_token');
    if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    } else {
    // we have to add the token to the url object
      url.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.request(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError (self: HttpService) {
    // we have to pass HttpService's own instance here as `self`
    return (res: Response) => {
      console.log(res);
      if (res.status === 401 || res.status === 403) {
        // if not authenticated
        console.log(res);
      }
      return Observable.throw(res);
    };
  }
}

다음 설정을 합니다.app.module.ts제공하기 위해XHRBackend▁the로서ConnectionBackend및 제자및RequestOptions사용자 지정 Http 클래스:

import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './services/http.service';
...
@NgModule({
  imports: [..],
  providers: [
    {
      provide: HttpService,
      useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new HttpService(backend, options);
      },
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [ AppComponent ]
})

그런 다음 이제 서비스에서 사용자 지정 http 공급자를 사용할 수 있습니다.예:

import { Injectable }     from '@angular/core';
import {HttpService} from './http.service';

@Injectable()
class UserService {
  constructor (private http: HttpService) {}

  // token will added automatically to get request header
  getUser (id: number) {
    return this.http.get(`/users/${id}`).map((res) => {
      return res.json();
    } );
  }
}

여기 포괄적인 가이드가 있습니다 - http://adonespitogo.com/articles/angular-2-extending-http-provider/

늦더라도 안하는 것보다는...=)

확장 개념을 사용할 수 있습니다.BaseRequestOptions(여기서 https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options) 에서 "즉시" 헤더를 새로 고칩니다(생성자뿐만 아니라).다음과 같이 getter/setter "headers" 속성 재정의를 사용할 수 있습니다.

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

    private superHeaders: Headers;

    get headers() {
        // Set the default 'Content-Type' header
        this.superHeaders.set('Content-Type', 'application/json');

        const token = localStorage.getItem('authToken');
        if(token) {
            this.superHeaders.set('Authorization', `Bearer ${token}`);
        } else {
            this.superHeaders.delete('Authorization');
        }
        return this.superHeaders;
    }

    set headers(headers: Headers) {
        this.superHeaders = headers;
    }

    constructor() {
        super();
    }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

이렇게 요청할 때마다 토큰을 설정했습니다.

import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';

export class CustomRequestOptions extends BaseRequestOptions {

    constructor() {
        super();
        this.headers.set('Content-Type', 'application/json');
    }
    merge(options?: RequestOptionsArgs): RequestOptions {
        const token = localStorage.getItem('token');
        const newOptions = super.merge(options);
        if (token) {
            newOptions.headers.set('Authorization', `Bearer ${token}`);
        }

        return newOptions;
    }
}

그리고 app.module.ts에 등록합니다.

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

다음은 Angular2 final용으로 업데이트된 승인된 답변의 개선된 버전입니다.

import {Injectable} from "@angular/core";
import {Http, Headers, Response, Request, BaseRequestOptions, RequestMethod} from "@angular/http";
import {I18nService} from "../lang-picker/i18n.service";
import {Observable} from "rxjs";
@Injectable()
export class HttpClient {

    constructor(private http: Http, private i18n: I18nService ) {}

    get(url:string):Observable<Response> {
        return this.request(url, RequestMethod.Get);
    }

    post(url:string, body:any) {   
        return this.request(url, RequestMethod.Post, body);
    }

    private request(url:string, method:RequestMethod, body?:any):Observable<Response>{

        let headers = new Headers();
        this.createAcceptLanguageHeader(headers);

        let options = new BaseRequestOptions();
        options.headers = headers;
        options.url = url;
        options.method = method;
        options.body = body;
        options.withCredentials = true;

        let request = new Request(options);

        return this.http.request(request);
    }

    // set the accept-language header using the value from i18n service that holds the language currently selected by the user
    private createAcceptLanguageHeader(headers:Headers) {

        headers.append('Accept-Language', this.i18n.getCurrentLang());
    }
}

물론 그것은 다음과 같은 방법으로 확장되어야 합니다.delete그리고.put필요한 경우(프로젝트의 현 시점에서는 아직 필요하지 않습니다).

은 은점중코적것입다니에 입니다.get/post방법

이 경우 인증확인을 위해 쿠키를 사용합니다. (의나 i18n헤필더니다습요했가는18▁for다▁header니18▁i▁i▁thethe▁needed습▁(필했요나)의 헤더가 필요했습니다.Accept-Language헤더)는 API에서 반환되는 많은 값이 사용자의 언어로 번역되기 때문입니다.제 앱에서 i18n 서비스는 현재 사용자가 선택한 언어를 보유하고 있습니다.

다음과 같이 별도의 서비스를 유지하는 것은 어떻습니까?

            import {Injectable} from '@angular/core';
            import {Headers, Http, RequestOptions} from '@angular/http';


            @Injectable()
            export class HttpClientService extends RequestOptions {

                constructor(private requestOptionArgs:RequestOptions) {
                    super();     
                }

                addHeader(headerName: string, headerValue: string ){
                    (this.requestOptionArgs.headers as Headers).set(headerName, headerValue);
                }
            }

그리고 당신이 다른 장소에서 이것을 부를 때 사용합니다.this.httpClientService.addHeader("Authorization", "Bearer " + this.tok);

추가된 헤더가 표시됩니다(예: - 다음과 같은 권한 부여).

여기에 이미지 설명 입력

몇 가지 조사 후에, 저는 결승전을 발견했고 가장 쉬운 방법은 연장하는 것입니다.BaseRequestOptions내가 더 좋아하는 것.
다음은 제가 어떤 이유로 시도했다가 포기한 방법들입니다.
를 펴다BaseRequestOptions 동헤더에서 constructor()제가 로그인하면 작동하지 않습니다.한 번 생성됩니다.그래서 그것은 역동적이지 않습니다.
를 펴다Http로, 저는 위와같이동헤수없에 할 수 .constructor()그리고 내가 다시 쓴다면,request(..)메소드 및 헤더를 다음과 같이 설정합니다.

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
 let token = localStorage.getItem(AppConstants.tokenName);
 if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
  if (!options) {
    options = new RequestOptions({});
  }
  options.headers.set('Authorization', 'token_value');
 } else {
  url.headers.set('Authorization', 'token_value');
 }
 return super.request(url, options).catch(this.catchAuthError(this));
}

이 메서드를 덮어쓰면 되지만 모든 get/post/put 메서드를 덮어쓸 수는 없습니다.

3입니다.제가 선호하는 솔루션은 확장입니다.BaseRequestOptions.merge():

@Injectable()
export class AuthRequestOptions extends BaseRequestOptions {

 merge(options?: RequestOptionsArgs): RequestOptions {
  var newOptions = super.merge(options);
  let token = localStorage.getItem(AppConstants.tokenName);
  newOptions.headers.set(AppConstants.authHeaderName, token);
  return newOptions;
 }
}

것이것merge()함수는 모든 요청에 대해 호출됩니다.

비록 제가 매우 늦게 답변을 드리지만 더 쉬운 해결책을 찾고 있는 사람이 있다면요.

Angular2-jwt.angular2-jwt는 Angular2 앱에서 HTTP 요청을 할 때 JSON 웹 토큰(JWT)을 Authorization 헤더로 자동으로 첨부하는 데 유용합니다.

고급 구성 옵션을 사용하여 글로벌 헤더를 설정할 수 있습니다.

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
        tokenGetter: (() => sessionStorage.getItem('token')),
        globalHeaders: [{'Content-Type':'application/json'}],
    }), http, options);
}

그리고 요청 토큰별로 전송하는 것은 다음과 같습니다.

    getThing() {
  let myHeader = new Headers();
  myHeader.append('Content-Type', 'application/json');

  this.authHttp.get('http://example.com/api/thing', { headers: myHeader })
    .subscribe(
      data => this.thing = data,
      err => console.log(error),
      () => console.log('Request Complete')
    );

  // Pass it after the body in a POST request
  this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
    .subscribe(
      data => this.thing = data,
      err => console.log(error),
      () => console.log('Request Complete')
    );
}

저는 기본 옵션을 재정의하는 아이디어가 마음에 드는데, 이것은 좋은 해결책인 것 같습니다.

그러나, 만약 당신이 연장할 수 있다면.Http수업. 이거 꼭 읽어주세요.

여기에 있는 일부 답변은 실제로 잘못된 오버로딩을 보여줍니다.request()확인하기 어려운 오류와 이상한 동작으로 이어질 수 있는 메서드입니다.저도 이걸 우연히 발견했어요.

이 솔루션은 다음을 기반으로 합니다.request() Angular에서 구현4.2.x하지만 미래에 호환될 수 있어야 합니다.

import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import {
  ConnectionBackend, Headers,
  Http as NgHttp,
  Request,
  RequestOptions,
  RequestOptionsArgs,
  Response,
  XHRBackend
} from '@angular/http';


import {AuthenticationStateService} from '../authentication/authentication-state.service';


@Injectable()
export class Http extends NgHttp {

  constructor (
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    private authenticationStateService: AuthenticationStateService
  ) {
    super(backend, defaultOptions);
  }


  request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

    if ('string' === typeof url) {

      url = this.rewriteUrl(url);
      options = (options || new RequestOptions());
      options.headers = this.updateHeaders(options.headers);

      return super.request(url, options);

    } else if (url instanceof Request) {

      const request = url;
      request.url = this.rewriteUrl(request.url);
      request.headers = this.updateHeaders(request.headers);

      return super.request(request);

    } else {
      throw new Error('First argument must be a url string or Request instance');
    }

  }


  private rewriteUrl (url: string) {
    return environment.backendBaseUrl + url;
  }

  private updateHeaders (headers?: Headers) {

    headers = headers || new Headers();

    // Authenticating the request.
    if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
      headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
    }

    return headers;

  }

}

식으로 하십시오. ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜimport { Http as NgHttp } from '@angular/http';이름 충돌을 방지하기 위해.

는 여서다는문제는루입니다.request()메서드에 두 개의 서로 다른 호출 서명이 있습니다.RequestURL 대신 개체가 전달되었습니다.string,options인수는 Angular에 의해 무시됩니다.따라서 두 사건 모두 적절하게 처리되어야 합니다.

다음은 재정의된 클래스를 DI 컨테이너에 등록하는 방법의 예입니다.

export const httpProvider = {
  provide: NgHttp,
  useFactory: httpFactory,
  deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};


export function httpFactory (
  xhrBackend: XHRBackend,
  requestOptions: RequestOptions,
  authenticationStateService: AuthenticationStateService
): Http {
  return new Http(
    xhrBackend,
    requestOptions,
    authenticationStateService
  );
}

이러한 접근 방식으로 주입할 수 있습니다.Http클래스는 정상적으로 작동하지만 재정의된 클래스는 마법처럼 주입됩니다.따라서 애플리케이션의 다른 부분(다형성)을 변경하지 않고도 솔루션을 쉽게 통합할 수 있습니다.

그냥추를 추가하세요.httpProvider에▁providers모듈 메타데이터의 속성입니다.

가장 단순한

성을 합니다.config.ts

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

export class Config {
    url: string = 'http://localhost:3000';
    httpOptions: any = {
        headers: new HttpHeaders({
           'Content-Type': 'application/json',
           'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
        })
    }
}

당신의 에.service가져오기만 하면 됩니다.config.ts

import { Config } from '../config';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class OrganizationService {
  config = new Config;

  constructor(
    private http: HttpClient
  ) { }

  addData(data): Observable<any> {
     let sendAddLink = `${this.config.url}/api/addData`;

     return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
       tap(snap => {
      return snap;
        })
    );
 } 

그게 가장 간단하고 안전했다고 생각합니다.

할 때( 큰 ▁that()이라는 이었습니다.appendHttpHeaders의 메서드가 원본 자체를 수정하지 않고 원본 개체의 복제본을 반환했습니다.그렇게headers.append('header', 'value')충분하지 않았습니다.결과를 다시 할당하거나 HTTP 호출에서 직접 사용해야 했습니다.

let headers = new HttpHeaders();
headers = headers.append('header', 'value');
this.http.get<any>('https://someulr.com/api/users', { headers });

일부 권한 부여 헤더를 사용하여 자체 http 클라이언트를 만들 수 있습니다.

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

@Injectable({
  providedIn: 'root'
})
export class HttpClientWithAuthorization {

  constructor(private http: HttpClient) {}

createAuthorizationHeader(bearerToken: string): HttpHeaders {
  const headerDict = {
    Authorization: 'Bearer ' + bearerToken,
  }
  return new HttpHeaders(headerDict);
}

get<T>(url, bearerToken) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.get<T>(url, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}

post<T>(url, bearerToken, data) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.post<T>(url, data, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}
}

그 다음에 주사를 놓는 거죠HttpClient서비스 클래스:

@Injectable({
  providedIn: 'root'
})
export class SomeService {

  constructor(readonly httpClientWithAuthorization: HttpClientWithAuthorization) {}

  getSomething(): Observable<Object> {
    return this.httpClientWithAuthorization.get<Object>(url,'someBearer');
  }

  postSomething(data) {
    return this.httpClientWithAuthorization.post<Object>(url,'someBearer', data);
  }
}

모든 요청에 대해 헤더를 계속 설정하는 대신 인터셉트를 사용할 수 있습니다.

나가는 모든 요청은 인증 헤더를 설정한 후 요청을 해제할 수 있는 인터셉터를 통과합니다.

각도 2.0.1 이상에 대해 몇 가지 변경 사항이 있었습니다.

    import {RequestOptions, RequestMethod, Headers} from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule }     from '@angular/http';
    import { AppRoutingModule } from './app.routing.module';   
    import { AppComponent }  from './app.component';

    //you can move this class to a better place
    class GlobalHttpOptions extends RequestOptions {
        constructor() { 
          super({ 
            method: RequestMethod.Get,
            headers: new Headers({
              'MyHeader': 'MyHeaderValue',
            })
          });
        }
      }

    @NgModule({

      imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
      declarations: [ AppComponent],
      bootstrap:    [ AppComponent ],
      providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
    })

    export class AppModule { }

더 간단한 솔루션을 선택할 수 있습니다 > 기본 옵션에 새 헤더 추가 api get(또는 기타) 함수로 병합 또는 로드합니다.

get(endpoint: string, params?: any, options?: RequestOptions) {
  if (!options) {
    options = new RequestOptions();
    options.headers = new Headers( { "Accept": "application/json" } ); <<<<
  }
  // [...] 
}

물론 기본 선택사항이나 클래스에 있는 모든 항목에서 이 헤더를 외부화할 수 있습니다.이는 Ionic에서 생성된 api.ts @Injectable() 내보내기 클래스 API {}에 있습니다.

그것은 매우 빠르고 나에게 효과가 있습니다.json/ld 형식을 원하지 않았습니다.

HTTP 인터셉트가 올바른 방법입니다.여기서 그것을 완전히 구현하는 방법에 대한 적절한 문서를 보지 못했기 때문에, 저는 구글의 공식 가이드에 대한 링크를 포함하고 있습니다.보안과 여러 개의 인터셉트 패키지를 사용할 경우 잠재적인 위험이 많기 때문에 구현하기 전에 문서를 읽어 보았습니다.

https://angular.io/guide/http#intercepting-requests-and-responses

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}
const headers = new HttpHeaders()
  .set('content-type', 'application/json')
  .set('x-functions-key', '');

return this.http.get<Person[]>(baseUrl, {
      headers: headers,
    });

추가 방법을 사용하여 기존 값 집합에 새 값을 추가합니다.

headers.append('Access-Control-Allow-Origin', '*')

사용할 수 있습니다.canActive다음과 같은 경로에서:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate() {
    // If user is not logged in we'll send them to the homepage 
    if (!this.auth.loggedIn()) {
      this.router.navigate(['']);
      return false;
    }
    return true;
  }

}

const appRoutes: Routes = [
  {
    path: '', redirectTo: '/deals', pathMatch: 'full'
  },
  {
    path: 'special',
    component: PrivateDealsComponent,
    /* We'll use the canActivate API and pass in our AuthGuard.
       Now any time the /special route is hit, the AuthGuard will run
       first to make sure the user is logged in before activating and
       loading this route. */
    canActivate: [AuthGuard]
  }
];

출처: https://auth0.com/blog/angular-2-authentication

언급URL : https://stackoverflow.com/questions/34464108/angular-set-headers-for-every-request

반응형