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

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

问题描述

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

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


解决方案

编辑: ,它更安全,建议使用 req.secure (如下)@Andy建议。虽然它使用类似的实现,它将是安全的将来使用,它还可以选择支持 X-Forwarded-Proto 头。



对于节点请求没有Express的对象:



它在 req.connection.secure (boolean)。



编辑:
API已更改,对于节点0.6.15 +



HTTPS连接具有 req.connection.encrypted (具有SSL连接信息的对象)。 HTTP连接没有 req.connection.encrypted



另外(从文档):


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



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;

解决方案

Edit: 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.

For node Request object without Express:

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

Edit: The API has changed, for Node 0.6.15+:

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

Also (from the docs):

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天全站免登陆