0
votes

Simple Node.js get a route that either sends a response status of 200 or 400 in a try-catch block.

If the server sends the 200 response, I can log that in my Axios get request (console.log(response.status)).

However, if the catch block runs and sends a status of 400, I just get the error in the browser displaying the error, and my response.status does not run. Why is this?

I want to render a message in my front end with react depending on the status that is being sent back. If code 400 is sent, then I want to retrieve that from the response in my frontend, but at the moment, it does not reach that.

Am I missing something about how these Node.js status codes work?

Thank you for your time

Here is the Node.js route

try {
        const user = req.user;
        res.status( 200 ).send();
    } catch ( e ) {
        res.status( 400 ).send();
    }

And here is the Axios get request

useEffect( () => {
        const call = async () => {
            let response = await axios( {
                method: "get",
                url: "/tasks"
            } );
            console.log( response );
            if ( response.status === 200 ) {
                setAuthorized( true );
                console.log( "We are authorized" );
            } else {
                setAuthorized( false );
                console.log( "We are not authorized" );
            }
        };
        call();
    } );
1

1 Answers

1
votes

The problem is that axios sees a 400 status as an error, and will do a throw. You can pass a parameter to axios to prevent this, and just pass it back.

Here is an example of how to do it using a validateStatus hook:

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})

For more information see "Handling errors" in https://github.com/axios/axios