简体   繁体   English

在 express.js 中间件请求中获取“#”后的 url

[英]get url after “#” in express.js middleware request

I need to get url on server middleware (using express.js).我需要在服务器中间件上获取 url(使用 express.js)。 I use req.url but when url starts from /#some/url req.url returns / ...我使用req.url但是当 url 从/#some/url req.url 开始返回/ ...

The same with req.path ..req.path相同..

Is there a way to get url after # in express.js?有没有办法在express.js中#之后获取url?

No. The part of the URL starting with the # symbol is never sent to the server.开始与URL的一部分#符号永远不会发送到服务器。

The # symbol in an URL is to introduce the fragment identifier . URL 中的#符号用于引入片段标识符 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).如果浏览器加载/#some/url ,它将有效地加载/ ,并跳转到id="some/url"的 HTML 元素(如果存在)。 The fragment identifier is only relevant to the browser, so it is not sent with the HTTP request.片段标识符仅与浏览器相关,因此不会与 HTTP 请求一起发送。

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.但是可以做的是使用客户端 Javascript 读取window.location.hash的值并使用 XMLHttpRequest 将其发送到服务器。 ( See other Stack Overflow post. ) 请参阅其他 Stack Overflow 帖子。

Any path/query param after # (Hash symbol) in URL will be removed by the browser. URL 中#(哈希符号)之后的任何路径/查询参数都将被浏览器删除。

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.这可以通过在 HTML/EJS 文件的脚本标签中用 EMPTY 字符串替换散列来解决,这将删除散列并且整个 URL 将被传递到服务器。

In case of a server side rendered application, applying the above technique in the 404 will route the redirection back to the valid router.在服务器端呈现的应用程序的情况下,在 404 中应用上述技术会将重定向路由回有效路由器。

<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.感谢我的队友进行此修复。

Use the built-in url module which is available in Node.js to parse the URL and create aurlObject .使用 Node.js 中提供的内置url模块来解析 URL 并创建一个urlObject This will have a hash fragment property containing the hash fragment you want.这将有一个包含您想要的散列片段的hash片段属性。

const url = require('url')
const urlObj = url.parse(req.url)
console.log(urlObj.hash) // #some/url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM