Wei Lun
Wei Lun

Reputation: 43

Angular HttpInterceptor htting 400 bad request when adding authorization header

I keep hitting HTTP error - 400 (bad request) when trying to add authorization header with HTTPInterceptor

I tested with Postman, and it works Tested with Postman

Here is the code:

Interceptor

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

@Injectable({
  providedIn: 'root'
})
export class InterceptrorService implements HttpInterceptor {

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    req = req.clone({
      setHeaders: {
    'x-api-key': 'a404823a-55b8-419e-bcbf-8ebb9ff7bae3',
    }
  });
  return next.handle(req);
 }

}

TestService

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

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

  constructor(private http: HttpClient) {
  }

  test() {
    return this.http.get('http://motorway:8000/wluntest/test');
  }
}

app.module

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

],

app.component

constructor(private test: TestService) {
  this.test.test().subscribe(value => console.log(value));
}

400 - bad request

The api is mock api constructed with Gravitee

Angular version

Angular CLI: 6.2.4
Node: 10.13.0
OS: linux x64
Angular: 6.1.9
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Http Interceptor log

Please help, thanks

Upvotes: 1

Views: 1557

Answers (3)

Wei Lun
Wei Lun

Reputation: 43

This is happened because of CROS in backend (Gravitee) Access-Control-Allow-Headers needed to configured to allow custom headers.

More info on : https://docs.gravitee.io/apim_publisherguide_configuring_cors.html

Upvotes: 0

Lucho
Lucho

Reputation: 1547

Your issue is that the response body is not a JSON object as the http-client wraps everything into Object(by default). So what you could do:

  • Change the response body into returning { msg: 'hello' } and in the callback pick it up by console.log(value.msg)
  • Or handle the fact its just plain text by adding {responseType: 'text'}, in your example:

    test() {
      return this.http.get('http://motorway:8000/wluntest/test', {responseType: 'text'});
    }
    

Upvotes: 1

Farhat Zaman
Farhat Zaman

Reputation: 1369

try to add headers like this.

req = req.clone({headers:req.headers.set('x-api-key','a404823a-55b8-419e-bcbf-8ebb9ff7bae3')});

Upvotes: 1

Related Questions