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.
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:
CodePudding user response:
This looks like mongodb and mongoose. .save()
returns an promise and should be resolved. You can do it with async / await here. 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 });
}
});