我想从请求中获取客户端请求的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/