I have a simple login route in express:
//login
router.post('/login',async (req,res) => {
try{
const user = await User.findOne({username: req.body.username});
console.log(user);
if (!user) {
return res.status(400).json({
success: false,
message: "username not found"
});
}
const validated = await bcrypt.compare(req.body.password,user.password);
if (!validated) {
console.log('password is wrong')
return res.status(400).json({
success: false,
message: "password not found"
})
}
const {password,...others} = user._doc;
res.status(200).json(others,{
success: true,
});
}
catch(err){
res.status(500).json(err);
}
})
I am using react for my frontend and axios to make requests:
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({type: 'LOGIN_START'});
try{
const res = await axios.post('http://localhost:5000/api/auth/login',{
username: userRef.current.value, //add the body
password: passwordRef.current.value
})
if (res.data.success) {
dispatch({type: "LOGIN_SUCCESS",payload: res.data})//if everything is fine save it into the localstorage.
}
console.log(res,"something went wrong")
}
catch(err) {
dispatch({type: "LOGIN_FAILURE"})
}
}
Now the problem is whenever i sent a status code of 400 it doesn't log the response which i want to see if i want to let the user know what's going on.
It just logs:
xhr.js:184 POST http://localhost:5000/api/auth/login 400 (Bad Request)
I want to see the content the json i am sending back. I didn't find any similar answers regarding this.
What am i missing?
CodePudding user response:
Axios 400 Bad request
, you could console.log(err.response)
in your catch block to get a more human-readable object.
axios
errors come in three types: message
, request
and response
.
catch(err) {
console.log(err.response);
dispatch({type: "LOGIN_FAILURE"})
}