Express - Get the route path

Express - Get the route path
0

#1

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”.


#2
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?


#3

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

Node Docs - url.pathname


#4

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


#5

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


#6

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


#7

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


#8

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.


#9

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:


#10

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.


#11

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.