Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express routes parameter conditions

People also ask

What are Express route parameters?

In Express, route parameters are essentially variables derived from named sections of the URL. Express captures the value in the named section and stores it in the req. params property. You can define multiple route parameters in a URL.

Are Express routes case sensitive?

The Express server framework allows developers to easily define routes for serving static pages or RESTful APIs; however, these routes are case-insensitive by default.

Which function arguments are available to Express route handlers?

The arguments available to an Express. js route handler function are: req - the request object. res - the response object.

How does Express define routes?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern. There are several ways to create routes.


Expanding on Marius's answer, you can provide the regex AND the parameter name:

app.get('/:id(\\d+)/', function (req, res){
  // req.params.id is now defined here for you
});

Yes, check out http://expressjs.com/guide/routing.html and https://www.npmjs.com/package/path-to-regexp (which express uses). An untested version that may work is:

app.get(/^(\d+)$/, function (request, response) {
  var id = request.params[0];
  ...
});

You can use:

// /12345
app.get(/\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});

or this:

// /post/12345
app.get(/\/post\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});