简体   繁体   English

即使出现“内部错误”,Rest API 也会返回状态代码 201

[英]Rest API return status code 201 even with a "internal error"

When a do a POST request with no body data it should return a status code 400, but it's returning a status code 201 with an empty object.当一个没有正文数据的 POST 请求时,它应该返回一个状态码 400,但它返回一个带有空对象的状态码 201。

This the code:这是代码:

router.post('/', (req: Request, res: Response) => {
const transaction = new Transactions({
    name: req.body?.name,
    amount: req.body?.amount,
    type: req.body?.type,
})
try{
    const newTransaction = transaction.save();
    return res.status(201).json(newTransaction);
}catch (err){
    return res.status(400).json({message: err.message});
}
})

This is the postman request and the response:这是邮递员的请求和响应:

邮递员请求

This looks like mongodb and mongoose.这看起来像 mongodb 和 mongoose。 .save() returns an promise and should be resolved. .save()返回一个承诺并且应该被解决。 You can do it with async / await here.您可以在此处使用 async / await 来完成。 What you return as an response is an pending promise.您作为响应返回的是待处理的承诺。

router.post("/", async (req: Request, res: Response) => {
  const transaction = new Transactions({
    name: req.body?.name,
    amount: req.body?.amount,
    type: req.body?.type,
  });
  try {
    const newTransaction = await transaction.save();
    return res.status(201).json(newTransaction);
  } catch (err) {
    return res.status(400).json({ message: err.message });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM