0

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,
        })
    }
}

1
  • If you feel an answer solved the problem, please mark it as 'accepted' by clicking the checkmark. This helps keep the focus on older SO which still don't have answers. Commented May 13, 2022 at 9:31

2 Answers 2

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})
}
Sign up to request clarification or add additional context in comments.

Comments

0

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})
}

2 Comments

If I use your approach, the error will be handled at userServices but i want it to be handled at Front end react because i want to display the error messages.
I know i just wanted to put you on the right path by mentioning the response attribute i will update the answer for more details

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.