如何在 Express 中获取完整 URL? [英] How to get the full URL in Express?
问题描述
假设我的示例网址是
我说我有以下路线
app.get('/one/two', function (req, res) {
var url = req.url;
}
url
的值为 /one/two
.
如何在 Express 中获取完整网址?例如,在上面的例子中,我想收到 http://example.com/one/two
.
How do I get the full URL in Express?
For example, in the case above, I would like to receive http://example.com/one/two
.
推荐答案
该协议可作为
req.protocol
使用.此处的文档
- 在 express 3.0 之前,除非您看到
req.get('X-Forwarded-Protocol')
已设置并具有值https
,在这种情况下,您知道这是您的协议
- Before express 3.0, the protocol you can assume to be
http
unless you see thatreq.get('X-Forwarded-Protocol')
is set and has the valuehttps
, in which case you know that's your protocol
主机来自 req.get('host')
正如 Gopal 所指出的
The host comes from req.get('host')
as Gopal has indicated
希望您的 URL 中不需要非标准端口,但如果您确实需要知道它,您会将其置于应用程序状态中,因为它是您传递给 app.listen 的任何内容
在服务器启动时.但是,在非标准端口上进行本地开发的情况下,Chrome 似乎将端口包含在主机标头中,因此 req.get('host')
返回 localhost:3000代码>,例如.因此,至少对于标准端口上的生产站点并直接浏览到您的 express 应用程序(没有反向代理)的情况,
host
标头似乎对 URL 中的端口做了正确的事情.
Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen
at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host')
returns localhost:3000
, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host
header seems to do the right thing regarding the port in the URL.
路径来自req.originalUrl
(感谢@pgrassant).请注意,这确实包括查询字符串.req.url 和 req.originalUrl 上的文档.根据您打算对 URL 执行的操作,与 req.url
相比,originalUrl
可能是也可能不是正确的值.
The path comes from req.originalUrl
(thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl
may or may not be the correct value as compared to req.url
.
将所有这些组合在一起以重建绝对 URL.
Combine those all together to reconstruct the absolute URL.
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
这篇关于如何在 Express 中获取完整 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!