Home > Software design >  expressjs optional url parameters
expressjs optional url parameters

Time:01-21

I'm trying to make simple app based on expressJS to return users (like API). I have /users route to get all users, which is ok.

app.get('/users', (req: express.Request, res: express.Response)

I need to add an optional parameter limit not to output all records. For example:

app.get('/users?limit=5', (req: express.Request, res: express.Response)

but limit param should be optional, so URLs like /users or /users?limit=5 or /users/limit/5 will be working.

Thank you.

CodePudding user response:

Don't modify the name of the route at all.

app.get('/users', will match /users with or without a query string.

Access data in the query string via req.query.

if (typeof req.query.limit !== 'undefined') {
    // a limit has been requested
}

CodePudding user response:

using app.get('/users?limit=5', (req: express.Request, res: express.Response) as route is a good way; you can provide the parameter or not when calling it;

(i don't know ho to do it in express/node but i reference it with php laravel to just show you the logic) So in your controller you put condition to make the query choosen executed; you store the prepared query inside variable;

$query = Model::myqueryBuilder();

so putting condition like

if($request->limit){
  $query = $query->limit($request->limit);
}

if you have another parameter you can make another condition; and in the end of our all parameter condition you execute the query

$query->get();

so you can conditionnaly use some query builder and execute all query prepared in the end;

I hope this logic helped you

CodePudding user response:

I think you need to create two endpoints.
First endpoint for '/users' and '/users?limit=5'

app.get('/users', (req: express.Request, res: express.Response) => {
    const { limit } = req.query
    console.log(limit)
})

Second endpoint for '/users/limit/5'


app.get('/users/limit/:limit', (req: express.Request, res: express.Response) => {
    const { limit } = req.params
    console.log(limit)
})
  •  Tags:  
  • Related