I'm currently working on a project using Angular 8 where I am making an HTTP post request to a .NET Core Web API. If the username or password is incorrect, the API returns a status code of 400. Despite the Chrome console indicating that a 400 status has been returned, I encounter a problem when trying to extract the status code from the observable returned by the HTTP request response. I receive an error message stating
Cannot read property 'message' of null
. Can anyone advise on how to resolve this issue? Thank you.
Login Component:
this.authService.login(
{
username: this.f.username.value,
password: this.f.password.value
}
)
.subscribe(
res => {
if(this.returnUrl != null){
this.router.navigate([this.returnUrl]);
}
else {
let role = res.role[0];
this.router.navigate([`${role}`]);
}
},
error => {
//The error occurs on this line. The error value is "cannot read message property of null" and error.status = undefined.
alert(error.status);
this.badCredentials = true;
this.router.navigate(['/login']);
});
Auth Service:
login(user: {username: string, password: string}) :Observable<any>{
return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user)
.pipe(
tap(response => this.doLoginUser(response)),
catchError((error): any => {
return throwError(`Connection Error: ${error}`);
}
));
}
UPDATE:
I have made changes to my Angular code as follows, but the error message remains the same:
Server returned code: undefined, error message is: Cannot read property 'message' of null
login(user: {username: string, password: string}) :Observable<any>{
return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user)
.pipe(
tap(response => this.doLoginUser(response)),
catchError(this.handleError));
}
handleError(err: HttpErrorResponse) {
let errorMessage = '';
if(err.error instanceof ErrorEvent){
//a client-side or network error occurred. Handle it accordingly.
errorMessage = `An error occurred: ${err.error.message}`;
} else {
//The back-end returned an unsuccessful response code.
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage);
}
When I use
return BadRequest("incorrect username or password.");
or return BadRequest();
in the Web API backend, I receive the error message Server returned code: undefined, error message is: undefined
. This seems to be related to how the error code is being returned from the backend API, but I am unsure about what needs to be fixed there.