Justin Elkow
Justin Elkow

Reputation: 2943

Node js Express Framework - regex not working

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?

Upvotes: 0

Views: 1396

Answers (2)

robertklep
robertklep

Reputation: 203359

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.

Upvotes: 3

Deathspike
Deathspike

Reputation: 8770

Pass a regular expression as string.

app.get('/(index\.html)?', function(req, res){
    res.set('Content-Type', 'text/plain');
    res.send('Hello from node!');
});

Upvotes: 1

Related Questions