4

I'm developing in Angular 8 and issuing a http post request to a .net core web api and returning a 400 status code if username or password is incorrect. Chrome console says 400 returned but when extracting the status code in the returned observable from the http request response, I get a Cannot read property message of null error message. How can I fix this? Thanks.

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 => {
            //This line throws the error. the value of error 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 updated my code to the following in my angular application and it still returns the same error message: 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 occured. Handle it accordingly.
      errorMessage = `An error occured: ${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);
  }

But when I do return BadRequest("incorrect username or password."); or return BadRequest(); it returns the error message Server returned code: undefined, error message is: undefined. So maybe this has to do with the way I'm returning the error code from the web api in the back end. I'm not sure what needs to be fixed there.

2
  • Where do you have that error ? Show us the code that have the error Commented Sep 9, 2019 at 9:46
  • @TonyNgo I'm getting the error message at the alert(error.status); line in the login component code that I posted above. I edited it to indicate where it occurs. That line throws the error: cannot read message property of undefined and when using the chrome debugger, it says error.status is undefined. Commented Sep 9, 2019 at 9:53

4 Answers 4

2

status is only provided if you observe: 'response'

try editting your authService like this

login(user: {username: string, password: string}) :Observable<any>{
    return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user
      // NEW CODE HERE
      { observe: 'response' }
    )
    .pipe(
      tap(response => this.doLoginUser(response)),
      catchError((error): any => {

              return throwError(`Connection Error: ${error}`);
          }
      ));
  }
Sign up to request clarification or add additional context in comments.

4 Comments

I changed it to this, but still getting that error message. return this.http.post<any>(${applicationPaths.loginApiUrl}, user, { observe: 'response' }). Is it the right syntax?
have you tried console logging the response and error?
I changed it to console.log(error.status) and it says "undefined" in chrome console.
I changed it to console.log(error) and it says: TypeError: Cannot read property 'message' of null
1

Add { observe: 'response' } to your code like this

login(user: {username: string, password: string}) :Observable<any>{
    return this.http.post<any>(`${applicationPaths.loginApiUrl}`, user, { observe: 'response' })
    .pipe(
      tap(response => this.doLoginUser(response)),
      catchError((error): any => {
              return throwError(`Connection Error: ${error}`);
          }
      ));
  }

Then try to access your errror data in your catchError like this

error.statusText
error.statusCode

Edit you should use this code in your controller

 return BadRequest();

Your code

return StatusCode(400);

only return status code

4 Comments

I tried it and it says in the console: Connection Error: undefined if I just try to output error it says: Connection Error: TypeError: Cannot read property 'message' of null
Can you show how you return data from .net core controller ?
I returned it like this: return StatusCode(400); But if I return it like this: return BadRequest("bad credentials"); it says Connection Error: Ok in console.
I changed it to return BadRequest() and console still says: TypeError: Cannot read property 'message' of null
0
  1. In your .NET API: return BadRequest("Incorrect username or password");
  2. In your Angular app:
    catchError((error): any => {
                  return throwError(`Connection Error: ${error.error}`);
              }
          ));

4 Comments

I tried this and it still gives the following error in console: Connection Error: undefined
what if you try return throwError(`Connection Error: ${error}`); ? that should return object of error to your console.
in my project it looks like this: this.http.get<Data[]>('apiUrl').subscribe(result => { this.chartData = result; }, error => { this.alertify.error(error.error); });
login in API: public IActionResult Login([FromBody] User user) { if (user == null) { return BadRequest("Invalid client request"); } try { } catch (HttpRequestException) { return BadRequest("Cannot connect to the IoT server."); } catch (Exception) { return BadRequest("Cannot login."); }
0

In my case I received this because I'd incorrectly annotated my API method as a HttpGet and not a HttpPost!

The message doesn't really seem to reflect this however when I fixed the API it worked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.