Ari
Ari

Reputation: 6189

How to handle missing param in route? Express

How do I handle a route that has a parameter, and if the client fails to include it, not let the server error out.

router.get('/:id', function(req, res, next) {
  let profileID = req.params.id
  if (profileID) {
    res.send('ID provided');
  } else {
    res.send('No id provided');
  }
});

If the ID parameter is provided I want to use it somewhere. But if it is missing, I want there to be a default behaviour to fall back to (ie. Route to another page, some message, etc)

The expected behavior is:

http://example.com/ routes to a landing page

But if a trailing ID is provided

http://example.com/abc123 routes to a specific profile

Upvotes: 0

Views: 1619

Answers (1)

Twiggeh
Twiggeh

Reputation: 1160

You can specify router.get('/:id?') and then id will be marked as an optional param.

CodeSandbox example

Express Server Example

// the question mark marks the parameter as optional
app.get("/:id?", (req, res) => {

  // will create an id entry even if none is provided
  console.log(req.params);

  // if there is an id do something else 
  if (req.params.id) return res.send(req.params.id);

  // if there is no id default behaviour for '/' route
  res.sendFile(__dirname + "/view/hello.html");
});

Upvotes: 3

Related Questions