I am currently writing an API which will require a user to pass an authentication token in the header of each request. Now I know I can create a catchall route say
Another way to make a catch-all route handler is this:
app.get('/login', function(req, res) {
//... login page
});
app.get('/', function(req, res) {
//...index page
});
app.get('/:pageCalled', function(req, res) {
console.log('retrieving page: ' + req.params.pageCalled);
//... mypage.html
});
This works exactly like robertklep's (accepted) answer, but it gives you more information about what the user actually requested. You now have a slug req.params.pageCalled to represent whatever page is being requested and can direct the user to the appropriate page if you have several different ones.
One gotchya to watch out for (thx @agmin) with this approach, /:pageCalled will only catch routes with a single /, so you will not get /route/1, etc. Use additional slugs like /:pageCalled/:subPageCalled for more pages (thx @softcode)
You can always place catch-all route after the ones you want to exclude (see robertklep answer).
But sometimes you simply don't want to care about the order of your routes. In this case you still can do what you want:
app.get('*', function(req, res, next) {
if (req.url === '/' || req.url === '/login') return next();
...
});
If you want to validate credentials or authenticity in every request you should use Express Routing feature "all", you can use it like this:
app.all('/api/*', function(req, res, next){
console.log('General Validations');
next();
});
You could place it before any Routing stuff.
Note that in this case I used "/api/" as path, you can use "/" you it fits your needs.
Hope it is not too late to help somebody here.
I'm not sure what you want to happen when a user accesses /login or /, but you can create separate routes for those; if you declare them before the catch-all, they get first dibs at handling the incoming requests:
app.get('/login', function(req, res) {
...
});
app.get('/', function(req, res) {
...
});
app.get('*', function(req, res) {
...
});