ℙℕℤℝ 2012-04-16 23:57
浏览 545
已采纳

如何在 Express 中获得完整的 url?

Let's say my sample url is

http://example.com/one/two

and I say I have the following route

app.get('/one/two', function (req, res) {
    var url = req.url;
}

The value of url will be /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.

转载于:https://stackoverflow.com/questions/10183291/how-to-get-the-full-url-in-express

  • 写回答

13条回答 默认 最新

  • 北城已荒凉 2012-04-17 05:12
    关注
    1. The protocol is available as req.protocol. docs here

      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
    2. The host comes from req.get('host') as Gopal has indicated

    3. 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.

    4. 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.

    Combine those all together to reconstruct the absolute URL.

      var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来