Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

express status code not updating, getting json message update

I am not getting status message as 500 eventhough I set. always getting status message as 200. how to set the status as 500?

here is my code : "express": "4.17.2",

    router.post('/register', async (req: Request, res: Response) => {
      const { password, email } = req.body;
      try {
        const isUserExist = await UserModel.findOne({ email: email });
        if (isUserExist) {
          //status not set.
          return res.json({ message: 'User already exist', success: false }).status(500);
        }
        const hashPassword = bcrypt.hashSync(password, 10);
        req.body.password = hashPassword;
        const newUser = new UserModel(req.body);
        await newUser.save();
        res.json({ message: 'user created successfully', success: true });
      } catch (error) {
        res.sendStatus(500).json({ message: 'Error creating user', success: false });
      }
    });

react axios:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

when i use:

return res.status(500).json({ message: 'User already exist', success: false }); getting something went wrong

export const registerUser = createAsyncThunk('post/user', async (user: RegisterFormProps) => {
  try {
    const response = await axios.post(environment.BASE_URL + '/user/register', user);
    console.log('suc', response.data.success);
    if (response.data.success) {
      toast.success(response.data.message);
    } else {
      toast.error(response.data.message);
    }
  } catch (error) {
    const err = error as AxiosError;
    console.log('err', err);
    toast.error('something went wrong');
  }
});

>Solution :

You should be using res.status instead of res.sendStatus in your code.

res.status(statusCode) just sets the status on the response.
whereas res.sendStatus(statusCode) sends the response after setting the status.

for example:

res.sendStatus(500); // equivalent to res.status(500).send(‘Internal Server Error’)

on the client side try using error.response.data in your catch block

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading