Here is my call from my code to log the error from axios call.
export const signUp=(formData, history)=>async(dispatch) =>{
try{
const {data}=await api.signUp(formData);
dispatch({type: AUTH, data});
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 (req, res)=>{
const {firstName, lastName, email, password, confirmPassword} = 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(password, salt);
try{
const newUser = await User.create({ firstName, lastName, email,
password:hashPassword, name:`${firstName} ${lastName}` });
const token=jwt.sign({email: newUser.email, id: newUser._id},
process.env.SECRET, {expiresIn: "1h"});
res.status(200).json({result:newUser, token});
}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=(formData, history)=>async(dispatch) =>{
try{
const {data}=await api.signUp(formData);
dispatch({type: AUTH, data});
history.push('/');
}catch(error){
console.log(error.response);
}
}
- config: {url: "/user/signUp", method: "post", data: "{\"0\":{\"firstName\":\"\",\"lastName\":\"\"
- ,\"email\":\"\",\"pas…\",\"password\":\"123123\",\"confirmPassword\":\"123123\"}",
- headers: {…}, baseURL: "http://localhost:4000", …}
- data: {message: "User already exist!"}
- headers: {content-length: "33", content-type: "application/json; charset=utf-8"}
- request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false,
- upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
- status: 400
- statusText: "Bad Request"
- __proto__: Object
No comments:
Post a Comment