-1

After 5 googling hours I cannot find any answer to my problem. I have an Http Interceptor used for auth service which is blocking the request to an external API(without Interceptor it is working just fine)

The code...

INTERCEPTOR

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

COMPONENT

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

'@angular/core';

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


}

SERVICE

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(

        );
      }



}

THE ERROR curs:1 Access to XMLHttpRequest at 'http://www.infovalutar.ro/2019/11/19/usd.bnr' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-headers is not allowed by Access-Control-Allow-Headers in preflight response. core.js:7187 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://www.infovalutar.ro/2019/11/19/usd.bnr", ok: false, …}

Is the same case with Angular interceptors and CORS

A B
  • 63
  • 2
  • 8
  • CORS errors occure in browsers if you try to access a resource with ajax which is from another site. Either `Authorization` or `Accept` as header is not allowed on the remote servers CORS policy. You have to check/modify the configuration of the remote servers to allow these headers in CORS requests. – Fussel Nov 24 '19 at 21:56
  • Remove whatever part of your frontend JavaScript code is adding an "access-control-allow-headers" request header. Access-Control-Allow-Headers is a response header, not a request header. Trying to set it as a request header will cause exactly the error cited in the question. – sideshowbarker Nov 25 '19 at 04:24

1 Answers1

0

You Need to register your interceptor into app.module.ts like this. First inport it import { HTTP_INTERCEPTORS } from '@angular/common/http'; and put this lines

 providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    }
}
Ashot Aleqsanyan
  • 2,894
  • 8
  • 19
  • I have one as per below: ... providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, ], bootstrap: [AppComponent] }) export class AppModule { } – A B Nov 25 '19 at 06:54
  • Please can you check this article from medium https://medium.com/@swapnil.s.pakolu/angular-interceptors-multiple-interceptors-and-6-code-examples-of-interceptors-59e745b684ec I am not sure but I think you need to put your interceptors into array like this ` providers: [ [{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }] ]` – Ashot Aleqsanyan Nov 25 '19 at 08:50