NodeJS multiple url in app.get Express

0

I have several (almost all) urls that 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 that, also files that I request to my site and etc, are redirected to the home, I would not want to have to create a new line for each url requested, like this:

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

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

Would it be possible to do something like the code below?

app.get('/urlA, /urlB', function(req, res){ 
    res.sendFile(__dirname+'/home.html');
});
    
asked by anonymous 21.07.2018 / 15:18

1 answer

1

Express allows you to 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 bit 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);
    
22.07.2018 / 00:10