javascript - expressjs : get requested url

标签 javascript node.js express

我想从请求中获取客户端请求的url。

目前我使用:

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

这根本不是很好。它还遗漏了我需要的 url 片段 (#/something)。

有没有办法获得完整的网址?也许在标题之外?

问候

最佳答案

您无法在服务器上获取 url 的片段(哈希部分),它不会被浏览器传输。

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.

来自 Fragment Identifier on Wikipedia

如果您想获得完整的 URL(没有片段标识符),最好的方法是使用包含端口的“Host” header 而不是 req.host,但其他方面与您当前所做的相同:

var requestedUrl = req.protocol + '://' + req.get('Host') + req.url;

关于javascript - expressjs : get requested url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12017111/

相关文章:

javascript - 如何在单击html中的按钮时将视频作为弹出窗口播放

javascript - 将参数值传递给 JavaScript 函数

google-chrome - NodeJS 和 Socket.io : Chrome not loading with WebSockets

javascript - Node.js 进程和退出代码未显示

node.js - NodeJS/Express 自动检测 SSL over HTTP (HTTPS) 解释?

javascript - 如何聚焦 HTML 表格中的行?

JavaScript:检查 URL 参数值的长度

javascript - Promise.all 返回更多值

javascript - Node JS 在 module.exports 中调用一个 "local"函数

node.js - connect-mongo session 集合为空