'AXIOS Status 400 Bad Request on React Front End

I am building an authentication component on React. When the wrong password/username is entered, I am expecting a Status 400 with the message: 'Invalid email or password' on the front end

Instead, I am getting Status 400 with the message: 'Request failed with status code 400'. I used postman to simulate a bad login and I do get the message : 'Invalid email or password'

When I tried a successful login on my frontend, everything works and I get a JWT token.

I also did a console.log on the backend and I can see that the data did reach the backend. The problem seems to be that the error is not handled by the front end properly.

Can someone take a look and let me know what is the problem? thank you.

Backend Post routes



router.post('/signin', async (req, res) => {
    console.log(req.body)
    let user = await User.findOne({ email: req.body.email })
    if (!user) return res.status(400).send('Invalid email or password')
    //compare the password with the password in database 
    const validPassword = await bcrypt.compare(req.body.password, user.password)
    if (!validPassword) return res.status(400).send('Invalid email or password')
    const token = user.generateAuthToken()
    // res.send(token)
    res.header('x-auth-token', token).send(_.pick(user, ['_id', 'name)', 'email']))
})

Frontend React

 doSubmit = async (e) => {
        e.preventDefault()
        const { data } = this.state

        try {
            console.log(data)
            await userService.signIn(data)
        } catch (ex) {
            console.log(ex.message)
            if (ex && ex.response.status === 400) {
                let errors = { ...this.state.errors }
                errors.email = ex.message
                this.setState({errors})
            }

        }
    }

userService

import axios from 'axios'
import { SIGN_UP, SIGN_IN } from '../Components/constant/constant';
import { Redirect } from 'react-router-dom';


export default {

    register: (user) => {

        console.log(user, 'axios')
        axios.post(SIGN_UP, {
            email: user.email,
            password: user.password,
            name: user.name
        }).then(function (response) {
            console.log(response, 'response')
            console.log(response)
            if (response.status === 200) {
                window.location = '/signupsuccessful'
            }
        })
            .catch(function (error) {
                console.log(error);
            })
    },

    signIn: async (data) => {
        console.log('sign in user service')
        await axios.post(SIGN_IN, {
            email: data.email,
            password: data.password,
        })
    }
}



Solution 1:[1]

I think you just missed the response part of the exception in the doSubmit function of the React code, so you get the exception message and not the response message from the request.

Change

errors.email = ex.message

To

errors.email = ex.response.data

Example

if (ex && ex.response.status === 400) {
  let errors = { ...this.state.errors }
  errors.email = ex.response.data
  this.setState({errors})
}

Solution 2:[2]

Nothing is wrong in your code just to get the response from the error case in axios you have to get like so:

...
.catch((error)=>console.log(error.response.data))

EDIT: for more details So what you have to do in your code is:

Backend

don't send a string i recommend send a json

res.status(400).send({message:'Invalid email or password'})

FrontEnd

if (ex && ex.response.status === 400) {
    let errors = { ...this.state.errors }
    errors.email = ex.response.data.message
    this.setState({errors})
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2