How to get the full url in Express?

Let's say my sample url is

http://example.com/one/two

and I say I have the following route

app.get('/one/two', function (req, res) {
    var url = req.url;
}

The value of url will be /one/two .

How do I get the full url in Express? For example, in the case above, I would like to receive http://example.com/one/two .


  • The protocol is available as req.protocol . docs here

  • Before express 3.0, the protocol you can assume to be http unless you see that req.get('X-Forwarded-Protocol') is set and has the value https , in which case you know that's your protocol
  • The host comes from req.get('host') as Gopal has indicated

  • Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host') returns localhost:3000 , for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host header seems to do the right thing regarding the port in the URL.

  • The path comes from req.originalUrl (thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl may or may not be the correct value as compared to req.url .

  • Combine those all together to reconstruct the absolute URL.

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

    Instead of concatenating the things together on your own, you could instead use the node.js API for URLs and pass URL.format() the informations from express.

    Example:

    var url = require('url');
    
    function fullUrl(req) {
      return url.format({
        protocol: req.protocol,
        host: req.get('host'),
        pathname: req.originalUrl
      });
    }
    

    I found it a bit of a PITA to get the requested url. I can't believe there's not an easier way in express. Should just be req.requested_url

    But here's how I set it:

    var port = req.app.settings.port || cfg.port;
    res.locals.requested_url = req.protocol + '://' + req.host  + ( port == 80 || po
    rt == 443 ? '' : ':'+port ) + req.path;
    
    链接地址: http://www.djcxy.com/p/70132.html

    上一篇: 所有的URL都是URN吗?

    下一篇: 如何在Express中获得完整的网址?