node.js - 如何知道 node.js 中的请求是 http 还是 https

标签 node.js express

我正在使用 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 会更快属性,可以是 httphttps。但是请注意,对于传出链接,您只需引用 //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/

相关文章:

node.js - 在我的主 Node.js 应用程序的子目录中运行 Ghost

javascript - async.whilst 中的 callback 和 err 是做什么用的?

javascript - 我的日期函数出现 Node JS 错误,出了什么问题?

node.js - 如何在快速路由中指定可选参数名称?

node.js - 使用 Connect-flash 和 Jade 的警报消息

javascript - process.env.API_URL 未定义

javascript - 如何从请求体中获取结果

node.js - 当 Google 日历事件更改时更新数据库

javascript - Gulp Browsersync + Babel Express 服务器无限期地等待本地主机

javascript - 解析: JavaScript Promises issue