如何获取快速的完整网址? [英] How to get the full url in Express?

查看:183
本文介绍了如何获取快速的完整网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例网址是


http://example.com/one/two

我说我有以下路线

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.

推荐答案


  1. 该协议可用作 req.protocol 此处的文档


  1. 在表达3.0之前,您可以假设协议为 http ,除非您看到 req.get('X-Forwarded-Protocol ')被设置,并且值 ht tps ,在这种情况下,您知道这是您的协议

  1. Before express 3.0, the protocol you can assume to be http unless you see that req.get('X-Forwarded-Protocol') is set and has the value https, in which case you know that's your protocol


  • 主机来自 req.get('host')如Gopal所示

    希望您不需要非标准端口,但是如果您确实需要知道,那么您将在应用程序状态下使用它,因为它是在服务器启动时传递给 app.listen 的任何内容。然而,在非标准端口的本地开发的情况下,Chrome似乎将端口包含在主机头中,因此 req.get('host')返回 localhost:3000 。因此,至少对于标准端口上的生产站点的情况,并直接浏览您的快速应用程序(不使用反向代理),主机标题似乎做了正确的事情

    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 可能或可能不是正确的值c>。

    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;
    

    这篇关于如何获取快速的完整网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆