3

I just created my first app with node.js and express. And I only want to print out current url, so I add these lines:

app.use('/test', function(request, response){
    console.log('current url is '+request.url);
    response.end();
})

Now when I run on browser at localhost:3000/test in will print me: current url is / Can someone explain it to me?

jpaljasma
  • 1,612
  • 16
  • 21

2 Answers2

7

i had the same issue and the solution was so obvious...

I had a "express rule" like:

app.all('*', function(req, res) {
    res.redirect('/')
})

And that redirect me automaticly to "/" route so it doesn't work...

In your case, I think the problem comes from your keywork "use" used with express. Try this:

app.get('/test', function(request, response){
    console.log('current url is '+request.url);
    response.end();
})
Axel Paris
  • 303
  • 3
  • 7
  • 1
    using get instead of use resolved this issue for me. app.use is in fact mounting middleware rather than routing requests. – Howie May 13 '19 at 22:02
  • The second part of this answer should be the accepted answer. – Daghall Jun 14 '23 at 06:57
4

Try for this:

var Url = req.protocol + '://' + req.get('host') + req.originalUrl;

Reference in StackOverflow: How to get full URL in Express.js

Community
  • 1
  • 1
Subburaj
  • 5,114
  • 10
  • 44
  • 87