Nodejs multiple url in app.get Express

Asked

Viewed 109 times

0

I have several (practically all) urls, which point to a single page and use the following line to send the file:

app.get('*', function(req, res){ 
    res.sendFile(__dirname+'/home.html');
});

But with this,also files that I request from my site and etc, are redirected to home, I would not like to have to create a new line for each requested url, so:

app.get('/urlA', function(req, res){ 
    res.sendFile(__dirname+'/home.html');
});

app.get('/urlB', function(req, res){ 
    res.sendFile(__dirname+'/home.html');
});

It would be possible to do something like the code below?

app.get('/urlA, /urlB', function(req, res){ 
    res.sendFile(__dirname+'/home.html');
});
  • Try app.get('/(urlA|urlB)', function(req, res) { ... }

  • I get Invalid regular Expression when I try to do this

1 answer

1


Express lets you pass a regular expression as the first parameter:

app.get(/(urlA|urlB)/, (req, res) => { ... });

Or:

app.get(/url(A|B)/, (req, res) => { ... });

Another option, a little more comprehensive:

app.get(/url[A-Z]/, (req, res) => { ... });

But you can also do something like this:

function exemplo(req, res) => { ... }
app.get('urlA', exemplo);
app.get('urlB', exemplo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.