Encountering the error "Unable to access property message of null" while trying to retrieve the error status code from an HTTP response in Angular

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.

Answer №1

Make sure to include the status parameter if you are using observe: 'response'

To update your authService, follow these steps:

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

              return throwError(`Connection Error: ${error}`);
          }
      ));
  }

Answer №2

To enhance your code, include { observe: 'response' } in the following way:

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, you can access your error data in the catchError block like this:

error.statusText
error.statusCode

Ensure to implement this code in your controller:

 return BadRequest();

Your current code:

return StatusCode(400);

Strictly return the status code only

Answer №3

  1. When creating your .NET API, make sure to include the following code snippet:
    return BadRequest("Incorrect username or password");
  2. Within your Angular application, remember to handle errors with the following code:
    catchError((error): any => {
                  return throwError(`Connection Error: ${error.error}`);
              }
          ));

Answer №4

I encountered a similar issue where I mistakenly labeled my API method as a HttpGet instead of a HttpPost.

Although the error message did not directly indicate this issue, resolving the API method type corrected the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Innovative concepts for designing web applications

Here's a unique situation that requires some brainstorming. I'm looking for any advice or suggestions. Imagine a tennis court equipped with sensors throughout - the net, lines, everything has sensors built in. These sensors are constantly sending ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

Oops! There seems to be a problem with the Node.js App. The MongooseError is indicating that the parameter `uri` in the `openUri()` function should be a string,

I've encountered an issue with my Next.js app involving MongoDB that I've been struggling to resolve. Hoping someone here can provide some insight and help me out. This is quite crucial for my project. First, I'll share the code from my serv ...

Having Trouble with Bootstrap 4: "Encountering Uncaught Error: Tooltip Transition in Progress"

I'm currently utilizing Bootstrap 4 on my website and incorporating the Tooltip feature. While my JavaScript appears to be correctly formatted, there are instances where I encounter errors in Console. My Javascript Setup | Bootstrap 4 <script src ...

Grab the SVG and resize it to a smaller scale

I have a small application built using Raphael.js that creates a node network with SVG and reorganizes it based on user selections. My goal is to capture the SVG image I've created and display it in a "mini-map" format at the bottom of the screen. Si ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Issue with the loop function

When I try to loop through my code, I keep getting the same "y" value (5) and it doesn't change. What I actually want is to make the ajax call repeat X times [all], passing both the response and the current call number through an anonymous function. A ...

What are some ways to enhance the loading time of my PHP-powered website?

Having troubles with my PHP-driven website that showcases real-time stock market data due to slow loading speeds. The site utilizes PHP for scraping financial information from external sources and presenting it on the front end. However, the performance is ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

What is the process of triggering a websocket connection event within the context of an express get request?

Having trouble incorporating WebSockets into Express's router.get request Here is the code snippet: app.js const { createServer } = require("http"); const mongoose = require('mongoose'); const config = require('./config'); const ...

Issues with routerLinkActive

On my page, I have a menu that uses the routerLinkActive attribute to add a green background when a link is active and grey when it's not. However, I'm facing an issue where the bg-success class is added but doesn't overwrite the bg-dark cla ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...

Turn off the ability to click on images, but allow users to access the right

https://i.stack.imgur.com/jriaP.png Example image sourced from reddit.com Illustration represents the desired effect using CSS and possibly JS. In essence: I aim to make an image on a website unclickable to its imageURL There should be a context menu ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection: { city: new york, country: usa addedBy: feibf78UYV3e43 // This is the USER ID ...

Creating a submodule in Angular is a great way to organize and modular

Currently, I am developing an angular 2 app using CLI. The size of my app module is becoming too large and complex, so I have decided to create submodules. The submodule structure is as follows: // Project Submodule import { NgModule } from & ...

When a child is added to a pixi.js sprite, it causes the child's size and position to become

Using typescript and pixi.js v4.8.2, I have implemented the following code to create containers: let appWidth = app.renderer.view.width let appHeight = app.renderer.view.height mapContainer = new PIXI.Sprite(PIXI.loader.resources.water_pattern ...

Unwrapping Promises in Angular for Seamless Resolution

I recently started working with Angular and found myself in a large project. I encountered a simplified version of my code below: var beforeClose = function() { var closeDeferred = $q.defer(), a = $q.defer(), b = $q.defer(), c = $q.defer() ...

Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message. Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68) Here is the code snippet in que ...

Issues arise when trying to type ChangeEvent in React using Typescript

After spending some time learning React with TypeScript, I encountered a problem. The prop onChangeHandler in my code takes a function to modify properties in formik values. <Formik<FormModel> initialValues={{ favorite: ...