Tuesday, July 20, 2021

how to access the server error mesage from axios http call?

 Here is my call from my code to log the error from axios call.

export const signUp=(formDatahistory)=>async(dispatch=>{
    try{
        const {data}=await api.signUp(formData);
        dispatch({type: AUTHdata});
        history.push('/');
    }catch(error){
        console.log(error);
    }
}

in the express server I have the code to send back the error message to client.

export const signUp=async (reqres)=>{
    const {firstNamelastNameemailpasswordconfirmPassword} = req.body;
    const existingUser=await User.findOne({email});
    if(existingUser){
        return res.status(400).json({error: "User already exist!"});
    }
    if(password !== confirmPassword){
        return res.status(400).json({error: "Password do not match"});
    }
    const salt = bcrypt.genSaltSync(10);
    const hashPassword = bcrypt.hashSync(passwordsalt);

    try{
        const newUser = await User.create({ firstNamelastNameemail
            password:hashPasswordname:`${firstName} ${lastName}` });
        const token=jwt.sign({email: newUser.emailid: newUser._id}, 
            process.env.SECRET, {expiresIn: "1h"});
        res.status(200).json({result:newUsertoken});

    }catch(err){
        console.error(err.message);
        res.status(500).json({message: 'Something went wrong'});
    }
}

the console only show the following error message, which is not helpful to trouble shooting and represent to the user. the status code is logged, but the error message is not shown.

 return res.status(400).json({error: "User already exist!"});

Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)


after I change the code to log the error.response, then we can finally get the error message back

export const signUp=(formDatahistory)=>async(dispatch=>{
    try{
        const {data}=await api.signUp(formData);
        dispatch({type: AUTHdata});
        history.push('/');
    }catch(error){
        console.log(error.response);
    }
}
  1. status400
  2. statusText"Bad Request"











No comments:

Post a Comment