3

I need to match 2 routes.

What is the meaning of this route /* ? . Means route like http://localhost:3000/#/ ?

Route check.

If route is /login or /register etc than hit it first otherwise /*

1 - route like /login or /register

app.get('What Here', function(req, res){
    res.redirect(req.url);
})

2 - route like /

app.get('/*', function(req, res){
    res.redirect('/');
})
Pirzada
  • 4,685
  • 18
  • 60
  • 113
  • I edited your question to clarify your needs. – verybadalloc Jun 08 '13 at 13:22
  • How to specify routes is most definitely in the express docs. To match /login, you write .get("/login"...). /* would match anything starting with a slash. Also, if you redirect to the same url you will create a redirect loop... – Andreas Hultgren Jun 08 '13 at 14:36
  • @andreas-hultgren, I already know that got many pages.Is there any way to use route on Path (directory) etc? – Pirzada Jun 08 '13 at 19:38
  • Then I'm not sure what you're asking for. get('/:paramName') would match any url that looks like /login or /register or/anything, and the path can be found in req.params.paramName. Is that what you're looking for? – Andreas Hultgren Jun 08 '13 at 21:14

1 Answers1

4

The way to go is the following:

app.get('/login', function (req, res) {
    //login user
});

For register, something similar

app.get('/register', function (req, res) {
    //register user
});

Finally, for everything else, you just do the following:

app.get(/^\/(.*)/, function (req, res) {
    //everything else
});

Obviously, you would have to place the first two route definitions before the last one.

For more details, check out Organize routes in Node.js

EDIT: As per your comment, and assuming you will want to handle "many pages" at each of these routes, you can do the following:

app.get('/login/:id', function (req, res) {
    //login user with id = id
    //The value of id = req.params.id
});

Other than that, to handle any route that starts with '/login/', try this regex:

app.get(/^\/login\/(.*)/, function (req, res) {
    //handles route like '/login/wefnwe334'
});
verybadalloc
  • 5,768
  • 2
  • 33
  • 49
  • You could also use `app.get(/^\/(?:register|login)/, ...)` if you wanted both `/register` and `/login` to run through the same code without having to define it twice. – Sly Jun 08 '13 at 15:12
  • And `app.get('*', ...)` as a catch-all route. – robertklep Jun 08 '13 at 18:59
  • @verybadalloc I can not use GET for individual routes. I got many pages. Is there any way to use route on Path (directory) etc? – Pirzada Jun 08 '13 at 19:36
  • @Rashid I'm not sure I understood your question. Are you wanting directories like `/register/` and `/login/` rather than `/register` and `/login`? – Sly Jun 08 '13 at 19:52
  • 1
    This answer is wrong, in that the anchor fragment is not sent to the server in the HTTP request, and therefore cannot be matched in routing. The server will never see it. – Brad Aug 21 '20 at 23:05