WagnerMatosUK
WagnerMatosUK

Reputation: 4429

How to setup interceptor header in Angular 6

I am trying to get an interceptor to work however I'm stumbling into a problem and I don't know where ti is. Here's my Interceptor code:

import { Injectable } from '@angular/core';
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor
} from '@angular/common/http';
import { AuthenticationService } from './../_services/index';
import { Observable } from 'rxjs/Observable';
import { AuthGuard } from './../_guards/auth.guard';

@Injectable()
export class Interceptor implements HttpInterceptor {
    constructor(public auth: AuthGuard) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        if (this.auth.getToken()) {
            console.log(this.auth.getToken());
            request = request.clone({
                setHeaders: {
                    Authorization: this.auth.getToken()
                }
            });
        }
        return next.handle(request);
    }
}

And every time I try a request, I see this:

Failed to load http://localhost:5000/api/stocks?all=true: Response for preflight is invalid (redirect) core.js:1633 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

If I remove the interceptor, additional calls are made and I get the 401 as expected but I still get the an error.

If I remove the interceptor AND the requirement to authenticate on the server, the request goes through (PS: Please ignore these errrors which are unrelated).

So I'm assuming this is not a CORS issue. Any ideas?

Upvotes: 0

Views: 4064

Answers (1)

Antoniossss
Antoniossss

Reputation: 32517

You got redirect on preflight - thus request is aborted. As you can also see, you got 301 on non-options requests. I can conclude that server is not configured to allow CORS properly - it should push simple answer to OPTIONS request (or reject it on purpose), but it is not doing that - insteed, server is redirecting like on GET request.

PREFLIGHT requests are not somethhing you can control - they are made by the brower, and server must handle those correctly - browser will refuse to perform such request otherwise.

Upvotes: 4

Related Questions