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