Reputation: 91845
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?
Upvotes: 30
Views: 16134
Reputation: 239
You can use this if your parameters has include slashes in it
app.get('/:href(*)', function(req, res) { ... })
It works for me. In my case, I used parameters like ABC1/12345/6789(10)
.
Hopefully this useful.
Upvotes: 2
Reputation: 3056
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.
Upvotes: 37
Reputation: 144912
Use a regular expression instead of a string.
app.get(/^\/(.+)/, function(req, res) {
var href = req.params[0]; // regexp's numbered capture group
});
Note that you cannot use the string syntax (app.get('/:href(.+)')
) because Express only allows a small subset of regular expressions in route strings, and it uses those regular expressions as a conditional check for that particular component of the route. It does not capture the matched content in the conditional, nor does it allow you to match across components (parts of the URL separated by slashes).
For example:
app.get('/:compa([0-9])/:compb([a-z]/')
This route only matches if the first component (compa) is a single digit, and the second component (compb) is a single letter a-z.
'/:href(.+)'
says "match the first component only if the content is anything", which doesn't make much sense; that's the default behavior anyway. Additionally, if you examine the source, you'll see that Express is actually forcing the dot in that conditional to be literal.
For example, app.get('/:href(.+)')
actually compiles into:
/^\/(?:(\.+))\/?$/i
Notice that your .
was escaped, so this route will only match one or more periods.
Upvotes: 36
Reputation: 1244
You can do this with regex routing
app.get('/:href(\d+\/\d+\/\d+\/*)', function(req, res) { });
I don't know if the regex is right, but you get the idea
EDIT:
I don't think the above works, but this does
app.get(/^\/(\d+)\/(\d+)\/(\d+)\/(.*)/, function(req, res) { });
Going to http://localhost:3000/2012/08/05/hello-i-must-be
yeilds req.params = [ '2012', '08', '05', 'hello-i-must-be' ]
Upvotes: 1