0

I am attempting to send a custom 'Body' message via Express response. I am able to do this successfully using:

res.send('Here is  my custom message');

However, if I attempt to apply a status (e.g. 400) then Express just completely ignores my custom body message:

res.status(400).send('Username and Password are both required.');

Instead of getting the 'Username and Password.....') message, I instead get the default: 'Bad Request'):

router.post('/login', (req, res, next) => {
  async function handleLogin() {
    try {
      const { username, password } = req.body;

      if (!username || !password) {
        res.status(400).send('Username and Password are both required.');
      }

      const authData = {
        username: username,
        password: password,
        grant_type: 'password'
      };

      const response = await axios.post(
        `${baseURL}/Token`,
        querystring.stringify(authData),
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
      );

      const data = await response.data;
      res.send(data);
    } catch (error) {
      console.log(error);
      res.status(400).send('Bad request has been received.');
    }
  }

  handleLogin();
});

I have tried:

res.status(400).send('Bad request has been received.');

&

res.status(400).json({ message: 'Message Here' })

&

res.status(400).send({ message: 'Message Here' })

I just cannot figure out why it will not send my custom message if I want to set a statusCode

  • https://stackoverflow.com/questions/14154337/how-to-send-a-custom-http-status-message-in-node-express – epascarello Sep 18 '19 at 12:57
  • I think that the message will not be sent as body request when the status is 400. So you have to catch the message in error handlers – med morad Sep 18 '19 at 13:08
  • The second one is within the catch statement (error) and that too will not render the custom string? – AW Kingston Sep 18 '19 at 14:15

0 Answers0