我正在使用 nodejs 和 expressjs。我想知道 clientRequest 对象中是否有类似 request.headers.protocol
的东西。我想为 Web 链接构建 baseUrl。因此,如果请求是通过 https 完成的,我想在所有链接中保留 https。
var baseUrl = request.headers.protocol + request.headers.host;
最佳答案
编辑: 对于 Express,它更安全,建议使用 req.secure
(正如@Andy 在下面推荐的那样)。虽然它使用类似的实现,但它对将来的使用是安全的,并且它还可以选择支持 X-Forwarded-Proto
header 。
话虽如此,对于您的用例,使用 Express' req.protocol
会更快属性,可以是 http
或 https
。但是请注意,对于传出链接,您只需引用 //example.com/path
,浏览器将使用当前协议(protocol)。 (另见 Can I change all my http:// links to just //?)
对于没有 Express 的 Node Request
对象:
它在 req.connection.secure
( bool 值)中。
编辑: 对于 Node 0.6.15+,API 已更改:
HTTPS 连接具有 req.connection.encrypted
(包含有关 SSL 连接信息的对象)。 HTTP 连接没有 req.connection.encrypted
。
另外(来自 the docs ):
With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.
关于node.js - 如何知道 node.js 中的请求是 http 还是 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348906/