When making a post request I get this error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
If somebody could explain why this is happening I would appreciate it :) Thanks
UPDATE
So, the this code POSTs successfully. But, when I uncomment the validation code I get that same error...
router.post("/", async (req, res) => {
//let client = validate(req.body);
//if (client.error) {
//res.status(400).json(result.error);
//return;
//}
let client = new Client(req.body);
try {
let savedClient = await client.save();
res.location(`/${savedClient._id}`).status(201).json(savedClient);
} catch (error) {
res.status(500).json(savedClient.error);
}
});
I don't see where you initialise savedClient and I think your error lies in your catch. You're referencing an object (savedClient) which doesn't appear to be in scope.
Try this:
router.post("/", async (req, res) => {
let client = new Client(req.body);
try {
let savedClient = await client.save();
res.location(`/${savedClient._id}`).status(201).json(savedClient);
} catch (error) {
console.log(error)
res.status(500).json(error);
}
});
maybe
let savedClient = await client.save();
I think it should be
...
} catch (error) {
res.status(500).json(savedClient.error);
}
because the promise's rejection error should be catch by the try/catch statement.