如何在 node.js 中知道请求是 http 还是 https [英] How to know if a request is http or https in node.js

查看:31
本文介绍了如何在 node.js 中知道请求是 http 还是 https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 nodejs 和 expressjs.我想知道 clientRequest 对象中是否有类似 request.headers.protocol 的东西.我想为 Web 链接构建 baseUrl.因此,如果请求是通过 https 完成的,我希望在所有链接中都保留 https.

I am using nodejs and expressjs. I wonder if there is something like request.headers.protocol in the clientRequest object. I would like to build the baseUrl for the web links. So if the request was done via https I would like to keep https in all links.

    var baseUrl = request.headers.protocol + request.headers.host;

推荐答案

对于 Express,它更安全,建议使用 req.secure(正如@Andy 在下面推荐的那样).虽然它使用了类似的实现,但将来使用是安全的,它还可以选择支持 X-Forwarded-Proto 标头.

For Express, it's safer and recommended to use req.secure (as @Andy recommends below). While it uses a similar implementation, it will be safe for future use and it also optionally supports the X-Forwarded-Proto header.

话虽如此,对于您的用例,使用 Express' req.protocol 属性,可以是 httphttps.但是请注意,对于传出链接,您可以直接参考//example.com/path,浏览器将使用当前协议.(另请参阅我可以将所有 http://链接更改为只是//?)

That being said, for your use case it would be quicker to use Express' req.protocol property, which is either http or https. Note, however, that for outgoing links, you can just refer to //example.com/path, and the browser will use the current protocol. (See also Can I change all my http:// links to just //?)

对于没有 Express 的节点 Request 对象:

For node Request object without Express:

它在 req.connection.secure(布尔值)中.

It's in req.connection.secure (boolean).

API 已更改,适用于 Node 0.6.15+:

The API has changed, for Node 0.6.15+:

HTTPS 连接具有 req.connection.encrypted(一个包含 SSL 连接信息的对象).HTTP 连接没有 req.connection.encrypted.

An HTTPS connection has req.connection.encrypted (an object with information about the SSL connection). An HTTP connection doesn't have req.connection.encrypted.

另外(来自文档):

使用 HTTPS 支持,使用 request.connection.verifyPeer() 和 request.connection.getPeerCertificate() 获取客户端的身份验证详细信息.

With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

这篇关于如何在 node.js 中知道请求是 http 还是 https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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