如果设置了.status,则表示忽略主体

时间:2019-09-18 12:06:30

标签: javascript node.js express

我正在尝试通过Express响应发送自定义的“正文”消息。我可以使用以下方法成功完成此任务:

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

但是,如果我尝试应用状态(例如400),则Express会完全忽略我的自定义正文消息:

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

我没有收到“ Username and Password .....”消息,而是获得了默认值:“ 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();
});

我尝试过:

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

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

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

我只是想不出为什么我要设置statusCode时为什么它不发送自定义消息

0 个答案:

没有答案
相关问题