首页 > 解决方案 > Http 拦截器在 Angular 中未正确接收 http 标头

问题描述

谷歌搜索 5 小时后,我找不到任何问题的答案。我有一个用于身份验证服务的 Http 拦截器,它阻止了对外部 API 的请求(没有拦截器它工作得很好)

编码...

拦截器

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

import { AuthenticationService } from '../services/auth.service';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        const currentUser = this.authenticationService.currentUser();
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`,
                    Accept: 'text/plain; charset=utf-8',

                }
            });


        }

        return next.handle(request);
    }
}

零件

import { Component, OnInit, ViewChildren, QueryList, ViewEncapsulation } from 

'@角/核心';

import { FormBuilder, Validators, FormGroup } from '@angular/forms';
// import { Router, ActivatedRoute } from '@angular/router';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
// import { of, Observable } from 'rxjs';

import { CursI } from './curs.model';


import { CursService } from './../curs.service';


@Component({
  selector: 'curs-valutar',
  templateUrl: './curs.component.html',
  styleUrls: ['./curs.component.scss'],
  providers: [CursService]

})

/**
 * InventoryList component - handling the inventorylist with sidebar and content
 */
export class CursComponent implements OnInit {


  curs: object;
  curslist: Array<CursI>;
  currency: string = '';
  date: string = '';
  entity: string = '';
  cursLaData: Array<string> = [];
  C: string = '';



  Currency: Array<string> = ['USD', 'EURO', 'Coroane suedeze'];
  validationform: FormGroup;

  constructor(private modalService: NgbModal, public formBuilder: FormBuilder, private service: CursService) {
    this.validationform = this.formBuilder.group({
      date: [''],
      currency: ['']
    });

  }


  ngOnInit() {

    // this._fetchData();
  }




  saveData() {
    const date = this.validationform.get('date').value;
    let currency = this.validationform.get('currency').value;

    this.curs = {
      date,
      currency,
    };


    if(this.validationform && currency === 'USD')
     {this.currency = 'usd'} else if (this.validationform && currency === 'EURO')
      {this.currency = 'eur'} 
      else {this.currency = 'sek'}



      this.modalService.dismissAll();

    this.date = date.replace(/-/g, '/');
    this.entity = this.date + '/' + this.currency + '.bnr';
    this.service.findCurs(this.entity).subscribe((data: any) => {
      (data => this.cursLaData = data);
      console.log(data);
    });

    console.log(this.cursLaData);
    console.log(this.curs);
    console.log(this.date);
    console.log(this.currency);
    console.log(this.entity);

  }

  /**
 * Modal Open
 * @param content modal content
 */
  openModal(content: string) {
    this.modalService.open(content, { centered: true, size: 'sm' });
  }


  onSubmit(values: object, form, modal) {
    if (values) {
      //post
      this.saveData();
      this.closeModal(form, modal);
    }
  }





  closeModal(form, modal) {
    form.reset();
    modal('close');
  }


}

服务

import { Injectable, PipeTransform } from '@angular/core';
import { CursModule } from './curs.module';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';

@Injectable({
    providedIn: 'root',

})

export class CursService {

  private apiurl = 'http://www.infovalutar.ro/';
  public entity: string;


    data: string;
    headers = new HttpHeaders().set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS').set('Content-Type', 'text/plain').set('Accept', 'text/plain').set('Access-Control-Allow-Headers', '*');
    httpOptions = {
      headers: this.headers,

    };

    constructor(private httpClient: HttpClient) {

    }


    public findCurs(entity: string) {
        return this.httpClient.get(`${this.apiurl}${entity}`, this.httpOptions).pipe(

        );
      }



}

错误 curs:1从源“ http://localhost:4200 ”访问“ http://www.infovalutar.ro/2019/11/19/usd.bnr ”的 XMLHttpRequest已被 CORS 策略阻止:请求标头Access-Control-Allow-Headers 在预检响应中不允许字段 access-control-allow-headers。core.js:7187 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: " http://www.infovalutar.ro/2019/11/19/usd.bnr ", ok: false , …}

Angular拦截器和CORS的情况相同

标签: angularhttpcorshttp-headersinterceptor

解决方案


您需要像这样将拦截器注册到 app.module.ts 中。首先导入它 import { HTTP_INTERCEPTORS } from '@angular/common/http'; 并放置这些行

 providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    }
}

推荐阅读