HttpClient cannot parse empty response

I have an interceptor that adds a token in the headers. However, if I use it after a POST request, my observer in the subscription does not start.

interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.inj.get(AuthService);
if (!this.authService.isLoggedIn()) {
  return next.handle(req);
}

const changedReq = req.clone({headers: req.headers.set('Authorization', `Bearer ${this.authService.getToken()}`)});
return next.handle(changedReq);
}

Services:

saveBeer(beerForm: BeerForm): Observable<Response> {
let body = JSON.stringify(beerForm);
let headers = new HttpHeaders({
  'Content-Type': 'application/json'
});

return this.http.post(this.apiUrl, body, {headers: headers});
}

Component:

onSubmitCreateBeer(): void {
this.beerService.saveBeer(this.beerForm)
  .takeUntil(this.ngUnsubscribe)
  .subscribe(
    (response: Response) => {
      // On response
      this.router.navigate(['/beers']);
    }, error => {
      // On error
    }, () => {
      // On complete
    });
}

My problem is that the answer does not work, so my navigation step does not work. If I turn off the interceptor, everything will work.

Any ideas?

+4
source share
2 answers

I have earned. The fact is that my observer expected an answer in response. However, after I get 200 OK, the answer does not contain anything in the body. This is an error, so the error function was called.

Solution 1 is to set responseType: text.

saveBeer(beerForm: BeerForm): Observable<any> {
let body = JSON.stringify(beerForm);
let headers = new HttpHeaders({
  'Content-Type': 'application/json'
});

return this.http.post(this.apiUrl, body, {headers: headers, responseType: 'text'});
}

Solution 2 is to return 204 from the backend.

Both work just fine. This is reported by the error message:

https://github.com/angular/angular/issues/18680

+8

- HttpInterceptor, , 200, HttpResponse ( , HttpClient 204 Not Content):

@Injectable()
export class EmptyResponseBodyErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
  .catch((err: HttpErrorResponse) => {
    if (err.status == 200) {
      const res = new HttpResponse({
        body: null,
        headers: err.headers,
        status: err.status,
        statusText: err.statusText,
        url: err.url
      });
      return Observable.of(res);
    } else {
      return Observable.throw(err);
    }
  });
 }
}
+1

Source: https://habr.com/ru/post/1689013/


All Articles