Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda