I am trying to use Reg Ex with an Express route in my Node app. I want the route to match the path '/' or '/index.html' but instead it matches EVERYTHING :(
Here's my route.
app.get(/\/(index.html)?/, function(req, res){
res.set('Content-Type', 'text/plain');
res.send('Hello from node!');
});
How can I get this regular expression to work?
Try this:
app.get(/^\/(index\.html)?$/, function(req, res){
res.set('Content-Type', 'text/plain');
res.send('Hello from node!');
});
Without the $, anything following the first / can still match, and the index.html is just an optional prefix. Without the ^, it will also match /something/index.html.
Pass a regular expression as string.
app.get('/(index\.html)?', function(req, res){
res.set('Content-Type', 'text/plain');
res.send('Hello from node!');
});