0

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?

4

2 回答 2

3

尝试这个:

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

如果没有$,第一个之后的任何内容/仍然可以匹配,并且index.html只是一个可选前缀。没有^,它也会匹配/something/index.html

于 2013-05-10T07:55:24.093 回答
1

将正则表达式作为字符串传递。

app.get('/(index\.html)?', function(req, res){
    res.set('Content-Type', 'text/plain');
    res.send('Hello from node!');
});
于 2013-05-10T07:55:09.370 回答