0

I have several routes implemented and I want to have express reach a default route before they are reached such as the following:

app.get('/', function(req,res,next){
  console.log('default route');
  // Do some work
  next('route');
}

Unfortunately this route is never reached, express simply passes by it. It does match, however, when I change the route slightly, like so:

app.get('/:bogus', function(req,res,next){
  ...
  next('route');
}

Why is the extra specificity needed? Why doesn't express always match on '/'?

  • Possible duplicate of [What does middleware and app.use actually mean in Expressjs?](https://stackoverflow.com/questions/7337572/what-does-middleware-and-app-use-actually-mean-in-expressjs) – Ayush Gupta Feb 15 '18 at 16:23
  • Please provide a complete example of the code and your expectations in order to see more clear your needs, like i have this routes I try to make a get to this route and it just does not happen... the order in your middleware matters and so it is not easy to answer this way. – juan garcia Feb 15 '18 at 16:29
  • @juangarcia, I have tried putting the above route at the very beginning of the middleware, and at the very end of the middleware but it made no difference. Quentin's answer explains why it wasn't working like I expected it to. – Josherwoodev Feb 15 '18 at 17:04

2 Answers2

0

/ is not the default route. It is the route for / and only / (query strings excepted).

/:bogus is the route for /something where "something" is whatever the client puts in the request.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

app.get() handle a specific path, http://localhost:8080/ is equivalent to /

/:bogus is for URL parameter, it's equivalent when you put something like: http://localhost:8080/HelloWorld

app.get('/:bogus', function(req, res){
    //console.log("Value is :"+req.params.bogus);
    res.send("Value is : "+req.params.bogus);
});

In the last line you can add this method, it is called by default when you enter a URL that is not defined in your routes

// After all your routes...
//Page Not Found
app.use(function(req, res){
    res.sendStatus(404);
});
iLyas
  • 1,047
  • 2
  • 13
  • 30
  • The only problem with that suggestion is that the urls I'm testing are all defined in my routes. I am simply trying to perform a man-in-the-middle operation with a default route before it reaches the correct endpoint. That is good to know, though. I will be using that consistently from now on for security purposes, thank you. – Josherwoodev Feb 15 '18 at 17:09