Home > Mobile >  How to display error message from express backend to react frontend?
How to display error message from express backend to react frontend?

Time:04-06

I was creating a MERN app and set up an error handler function that displays error messages whenever certain criteria were not met. In my case, I have a sign up page that requires an email to be valid and also the password to be at least 6 characters. Right now these messages are showing accurately on my backend's console in VS Code, but I am having trouble showing them on my browser's/frontend's console. I looked at this SO post but still have no luck in solving my issue. I suspect that it is because my frontend and backend are on different ports but I still don't know how to fix it. Code is posted below.

Route code

const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { email: '', password: ''};


    //duplicate error code
    if(err.code === 11000){
        errors.email = "that email is already registered";
    }

    //Just a way to create custom error messages
    if(err.message.includes("Creator validation failed")){
        Object.values(err.errors).forEach(({properties}) => {
            errors[properties.path] = properties.message;
        });
    }

    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'efrgvwrtgr435f345secret', {
        expiresIn: maxAge
    });
}

router.route('/add').post((req,res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const bio = req.body.bio;
    const creatorName = req.body.creatorName;
    const password = req.body.password;
    const email = req.body.email;

    const newCreator = new Creator({firstName, lastName, bio, creatorName, password, email})

        newCreator.save()
        .then(() => { 
            const token = createToken(newCreator._id);
            res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000}).json("Token is "   token);
            // res.json("New creator added!");
            res.send("New creator added!");
            
        })
        // .catch((err) => { const errors = handleErrors(err); res.status(404).json({ errors })});
        .catch((err) => { const errors = handleErrors(err); res.status(404).send({ errors })});
})

Submit action code from signup page

const handleSubmit = (e) => {
        e.preventDefault()

        const creator = {
            firstName: firstName,
            lastName: lastName,
            creatorName: creatorName,
            bio: bio,
            creatorName: creatorName,
            password: password,
            email: email
        }

        console.log(creator);
        
//If there are any errors when the submit btn was clicked, I want those errors to be displayed on the browser's console
        try {
            axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
            // .then((res) => console.log(res.data))
            .then((res) => console.log(res.json));
            history.push('/marketplace');
        }
        
        catch (err) {
            console.log(err);
        }
    }

CodePudding user response:

When you send the response using res.status(404).send({ errors }) you get to tell the client the error code - Axios has a way to catch all codes that do not fall within the 200 (OK) range. Essentially, if an error code is sent with the response, you can see the data of the error using error.response.data:

axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
    .then((res) => console.log(res.json))
    .catch((error) => {
        if(error.response) console.log(error.response.data);
    })

Source: https://axios-http.com/docs/handling_errors

  • Related