Peter G. Horvath
Peter G. Horvath

Reputation: 545

Accessing response body in Angular when HTTP Post fails with error 403

I have an Angular 9 project where I perform login via a HTTP post using HttpClient. If login fails, HTTP 403 is returned with a JSON response that contains the error message to be displayed on the UI.

My problem is that my error handler is always called with a simple string Forbidden, instead of the response body I want. How could I retrieve the response body? It is properly returned to the browser.

I have something like this:

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

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

    constructor(
        private http: HttpClient,
        // ...
    )


    login(userName, userPassword) {
        return this.http.post(`login`, {user: userName, password: userPassword}); 
    }
}

I have a component, which simply retrieves the error returned and shows it on the UI.

this.accountService.login(this.f.username.value, this.f.password.value)
    .subscribe(
        data => {
            this.router.navigate([this.returnUrl]);
        },
        error => {
            // error is a string here
            this.alertService.error(error.errorMessage); 
            this.loading = false;
        });

Upvotes: 0

Views: 1482

Answers (1)

Hristiyan Yanev
Hristiyan Yanev

Reputation: 86

If you want to display some error message from your response you can achieve this by creating an error interceptor.

Check this and this

Upvotes: 0

Related Questions