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