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",'/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);
        res.json({ message: 'user created successfully', success: true });
      } catch (error) {
        res.sendStatus(500).json({ message: 'Error creating user', success: false });

react axios:

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 + '/user/register', user);
    if ( {
    } else {
  } 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 in your catch block

Leave a ReplyCancel reply