0

Node アプリの Express ルートで Reg Ex を使用しようとしています。ルートをパス「/」または「/index.html」に一致させたいのですが、代わりにすべてに一致します:(

これが私のルートです。

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

この正規表現を機能させるにはどうすればよいですか?

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 に答える