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?
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. )
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.