Reputation: 1406
Let's say I have a route /ressource
. I can call this route with a query parameter /ressource?param=ABC
which I can retrieve in Node with:
app.get('/ressource', function (req, res) {
const parameter = req.query.param
})
Now, is there a predefined way I can require the parameter which throws an error for request to /ressource
without ?param=ABC
.
Upvotes: 3
Views: 7435
Reputation: 5069
You can use req.query to get the query parameter and use next
callback function to throw an error like
app.get('/ressource', function (req, res, next) {
if(!req.query.param) {
const err = new Error('Required query params missing');
err.status = 400;
next(err);
}
// continue
const parameter = req.body.param
})
Upvotes: 5
Reputation: 6263
There are no predefined way to. You can choose to check it yourself inside the callback function:
if (!req.query.parameter) {
res.send('parameter is missing');
}
or to use a router middleware which would serve the same purpose
Upvotes: 0