Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs: get requested url

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

Currently I use:

var requestedUrl = req.protocol + '://' + req.host + ':3000' + req.url;

This isn't really nice at all. It also leaves out url fragments I require (#/something).

Is there a way I can get the complete url? Maybe out of the header?

Regards

like image 779
bodokaiser Avatar asked Aug 18 '12 08:08

bodokaiser


People also ask

What is request URL in node JS?

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.


2 Answers

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;
like image 114
Raoul Avatar answered Sep 20 '22 13:09

Raoul


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.

like image 24
lostintranslation Avatar answered Sep 20 '22 13:09

lostintranslation