Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs routing to match specific urls

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('/');
})
like image 230
Pirzada Avatar asked Oct 16 '25 15:10

Pirzada


1 Answers

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'
});
like image 110
verybadalloc Avatar answered Oct 18 '25 07:10

verybadalloc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!