expressjs: get requested url

后端 未结 4 1918
情深已故
情深已故 2021-02-19 07:02

I want to get the url the client has requested out of the request.

Currently I use:

var requestedUrl = req.protocol + \'://\' + req.host + \':3000\' + re         


        
相关标签:
4条回答
  • 2021-02-19 07:23

    I'm afraid that pretty much all you can do. Unless you using https you can assume the protocol as http. As Raoul said you are not able to get anything after # server-side, that's for the browser

       var requestedUrl =  'http://' + req.headers.host + ':3000'  + req.url
    
    0 讨论(0)
  • 2021-02-19 07:30

    I often times add something like this to my express app:

      app.use(function(req, res, next) {
        req.getRoot = function() {
          return req.protocol + "://" + req.get('host');
        }
        return next();
      });
    

    Now you have a function you can call on demand if you need it.

    0 讨论(0)
  • 2021-02-19 07:33

    Is this that you are looking for ?

    req._parsedUrl.pathname
    

    You should, if you don't already use:

    var util = require('util'); // core module
    console.log(util.inspect(req));
    

    To debug find out that kind of data.

    0 讨论(0)
  • 2021-02-19 07:41

    You cannot get the fragment (hash section) of a url on the server, it does not get transmitted by the browser.

    The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the server — of course the server typically helps to determine the MIME type, and the MIME type determines the processing of fragments. When an agent (such as a Web browser) requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent processes the resource according to the document type and fragment value.

    From Fragment Identifier on Wikipedia

    If you want to get the complete URL (without the fragement identifier), the best way would be to use the "Host" header which includes the port rather than req.host but otherwise the same as you are currently doing:

    var requestedUrl = req.protocol + '://' + req.get('Host') + req.url;
    
    0 讨论(0)
提交回复
热议问题