Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow slashes in my Express routes?

I'm attempting to implement permalinks, in the form /2013/02/16/title-with-hyphens. I'd like to use route parameters. If I try the following route:

app.get('/:href', function(req, res) { }); 

...then I get a 404, presumably because Express is only looking for one parameter, and thinks that there are 4.

I can work around it with /:y/:m/:d/:t, but this forces my permalinks to be of that form permanently.

How do I get route parameters to include slashes?

like image 420
Roger Lipscombe Avatar asked Feb 16 '13 21:02

Roger Lipscombe


People also ask

What is a wildcard route Express?

Express allow you to use a wildcard within a route path using * . For example, the path defined below can be access using anything that follows the base URL (for example, if you wanted to build a “catch all” that caught routes not previously defined). app. get('/*',function(req,res) { req. send("I am Foo"); });

How do you protect Express routes?

The ensureAuthenticated function is just an example, you can define your own function. Calling next() continues the request chain. No idea, if you want to protect a set path you can use middleware e.g app. use('/user/*', ensureAuthenticated) will protect any matching routes.

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.


1 Answers

It seems that app.get("/:href(*)", ...) works fine (at least in Express 4). You will get your parameter value in req.params.href.

It will also be fired by / route, which is probably not what you want. You can avoid it by setting app.get('/', ...) elsewhere in your app or explicitly checking for an empty string.

like image 54
Tad Lispy Avatar answered Sep 17 '22 04:09

Tad Lispy