hoan
hoan

Reputation: 1406

Express require a query parameter

Let's say I have a route /ressource. I can call this route with a query parameter /ressource?param=ABCwhich 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

Answers (3)

Arif Khan
Arif Khan

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

Robdll
Robdll

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

Daksh M.
Daksh M.

Reputation: 4809

In express, query is automatically parsed and put into the req.query object, not the req.param object.

So you can access it like this:

const parameter = req.query.parameter;

read req.query on expressjs docs.

Upvotes: 0

Related Questions