39

I need to get url on server middleware (using express.js). I use req.url but when url starts from /#some/url req.url returns /...

The same with req.path..

Is there a way to get url after # in express.js?

Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • 4
    possible duplicate of [How to get Url Hash (#) from server side](http://stackoverflow.com/questions/317760/how-to-get-url-hash-from-server-side) – Jonathan Lonowski Jul 19 '13 at 10:50
  • 3
    There's a good explanation here http://stackoverflow.com/questions/3664257/why-the-hash-part-of-the-url-is-not-in-the-server-side – Guidone Jul 19 '13 at 12:35
  • The #-part is not transferred to the server. – Magnus Bodin Nov 30 '16 at 16:17
  • Does this answer your question? [Why is the hash part of the URL not available on the server side?](https://stackoverflow.com/questions/3664257/why-is-the-hash-part-of-the-url-not-available-on-the-server-side) – rxgx Aug 03 '22 at 22:05

3 Answers3

61

No. The part of the URL starting with the # symbol is never sent to the server.

The # symbol in an URL is to introduce the fragment identifier. This is used to link to a specific part of the page. If a browser loads /#some/url, it will effectively load /, and skip to the HTML element with id="some/url" (if present). The fragment identifier is only relevant to the browser, so it is not sent with the HTTP request.

What you however can do, is using client side Javascript to read out the value of window.location.hash and send it to the server using an XMLHttpRequest. (See other Stack Overflow post.)

dusk
  • 1,799
  • 18
  • 25
2

Any path/query param after # (Hash symbol) in URL will be removed by the browser.

This can be handled by a small hack by replacing the hash with an EMPTY string in the script tag of HTML/EJS file which will remove the hash and the entire URL will be passed to the server.

In case of a server side rendered application, applying the above technique in the 404 will route the redirection back to the valid router.

<script>
  const hash = window.location.hash;
  if(hash.length > 0 && hash.includes("#/")) {
    window.location.replace(window.location.href.replace('#/',''));
  }
</script>

This worked well in my application. Thanks to my teammates for this fix.

Selvam Raju
  • 196
  • 4
  • 14
-5

Use the built-in url module which is available in Node.js to parse the URL and create a urlObject. This will have a hash fragment property containing the hash fragment you want.

const url = require('url')
const urlObj = url.parse(req.url)
console.log(urlObj.hash) // #some/url
Alex Chesters
  • 3,380
  • 5
  • 19
  • 27
  • 6
    Unless the `#`-part is not transferred to the server. – zerkms Nov 14 '16 at 22:13
  • I tried in local, I run a url like: over-1000-car-911-white-vin#lala, then in nodejs, console.log('req.url ', url.parse(req.url)) console.log('req.originalUrl ', url.parse(req.originalUrl)) and the hash symbol is never read as you say – Erick Garcia Mar 10 '20 at 14:46