Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
Error is thrown and caught in the backend but the fronted React does not catch the error

I was doing a course in MERN Stack and during that I encountered a problem. For one form submission page the backend error handling was done in this way:

router.put('/education' , [auth , 
  check('school','School is required').notEmpty(),
  check('degree','Degree is required').notEmpty(),
  check('fieldofstudy','Field of Study is required').notEmpty(),
  check('from','From date is required').notEmpty()
],
async (req,res)=>{
  const errors = validationResult(req);
  if(!errors.isEmpty()){
    return res.json({ errors:errors.array()});
  }

  const {  
    school,
    degree,
    fieldofstudy,
    from,
    to,
    current,
    description
   } = req.body;

   const newEdu = {
    school,
    degree,
    fieldofstudy,
    from,
    to,
    current,
    description
   }


   try {
     const profile = await Profile.findOne({ user: req.user.id })
    if(profile) console.log('profile found req body is', req.body )
     profile.education.unshift(req.body);
     console.log('unshifted')
     await profile.save(); 

     res.json({ profile })
   } catch (err) {
     res.status(500).send("Server Error");
   }
})  

Now if I use Postman to to send some blank raw data as the inputs of the form, It does give back the errors that it is supposed to.

The frontend code used to make this request looks something like this:

export const addEducation = (formData, navigate )=> async dispatch => {
try {
    const res = axios.put('http://localhost:5000/api/profile/education',formData)
    dispatch({
        type: UPDATE_PROFILE,
        payload: res.data
    });

    dispatch(setAlert('Education Added', 'success'))
    navigate('/dashboard')      

} catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
        errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
    }
    dispatch({
        type: PROFILE_ERROR,
    });
}
}

The formData is sent through the form page upon Submission of the form.

What this code does is even if all the fields are empty, it just submits the form and sets the alert to 'Education Added' and navigates to '/dashboard'. The database shows no entry of a empty Education field whatsoever. Also the input tags in the form do not have 'required' attribute set.

Why isn't it catching the errors and setting alerts for them?

I am fairly new to MERN so any help will be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda