Express - Get the route path

For example I have
localhost:3000/hey and I want to get “hey”, localhost:3000/getme and I want to get “getme”.

I’ve tried using “req.route.path” and “req.originalUrl”.

app.get('/:name', function(req, res) {
    // the user was found and is available in req.user
    res.send('What is up ' + req.name + '!');
});

How about this one?

You can check the url node module ( url.pathname seems to fit you usecase):

Node Docs - url.pathname

Do you also know a way to do the debugging in express? I can’t seem to be able to use console.log().

Did it gives you some errors? console.log() should works ^^

It doesn’t give me any error but I don’t get anything in the console.

The output goes in the terminal usually, not in the browser’s console. Could it be this?

1 Like

I also thought it could have been printed in the terminal but nope.
I’ve just noticed that I don’t have nodemon in the scripts, it might be that, so everytime it saves it doesn’t reload.

Nodemon is not related to console.log, if you still experience this issue post the code, i’m sure we can figure it out :stuck_out_tongue:

I was able to do that with this code:

app.get('/:sth', function (req, res) {
	console.log(req.url);
    
    res.render('index', {
        title: 'Population Chart'
    });
});

I get “/getme” instead of “getme” but it doesn’t matter at all since I can do a s.substr(1) if necessary.

I looked into the documentation you sent me before and I really like it, since I am pretty new to nodejs.

Thank you for everything anyway, it was really helpful.

1 Like

If you’re using express, I think the best way to retrieve URL parameters is by using req.params. I think it is a bit easier. For example.

app.get(/:name,  function (req, res) {
  console.log(req.params.name);
});

You can get the parameters without forward slash.