When I call a GET request in Postman with the url “localhost:3000/api/users/id/” without the number of the ID, I’d like to have a return like this one when I call a GET request with the query empty:
{
"errors": [
{
"type": "field",
"msg": "Must not be empty",
"path": "filter",
"location": "body"
}
}
but insteaded this is the return I have:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/users/id/</pre>
</body>
this the code:
app.get("/api/users/id/:id", findUserIndex, checkSchema(getUserValidationIdSchema), (req, res) => {
const result = validationResult(req);
const {userIndex} = req;
if (!result.isEmpty()) return res.status(400).send({errors: result.array()});
if (result.isEmpty()) return res.send(users[userIndex]);
})
this is the function finderUserIndex:
const findUserIndex = (req, res, next) => {
const {params: {id}} = req;
const parsedId = parseInt(id);
if (isNaN(parsedId)) return res.sendStatus(400);
const userIndex = users.findIndex((user) => user.id === parsedId);
if (userIndex === -1) return res.sendStatus(404);
req.userIndex = userIndex;
req.parsedId = parsedId;
next();
}
and this is the schema get getUserValidationIdSchema:
export const getUserValidationIdSchema = {
id: {
notEmpty: {errorMessage: "Must not be empty"},
}
}