Node.js https.server API解析

Node.js HTTPS服务器搭建
本文介绍了如何使用Node.js创建HTTPS服务器及客户端请求的过程。详细解释了HTTPS模块的配置选项,并展示了具体的代码示例。

    web加密传输技术:

/**
 * Created by Antianlu on 14-5-7.
 * HTTPS是一个基于TLS/SSL的HTTP协议,在Node中作为一个独立的模块实现
 */

var https = require('https');
var fs    = require('fs');

/**
 * 以下为全部参数列表,如果使用了出key和cert或者pfx之外的其他参数,是在客户端代理中使用。
 * pfx: 证书, 用于SSL的私秘钥证书文件. 默认 null.
 * key: 为SSL提供秘钥. 默认 null.
 * passphrase: 为 私秘钥 或者 pfx提供通行证字符串. 默认 null.
 * cert: 使用公共 x509证书. 默认 null.
 * ca: 权威证书或数组的权威证书检查远程主机.
 * ciphers: A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.
 * rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.
 * secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
 * @type {{key: *, cert: *}}
 */
var options = {
    key : fs.readFileSync('certs/agent2-key.pem'),
    cert: fs.readFileSync('certs/agent2-cert.pem')
};

/**
 * 创建https服务器,很多于http服务器相同,只是部分参数配置不一
 * @param {Object} options 配置  另一种配置为:var optinos = {pfx : fs.readFileSync('server.pfx')}
 * @param {Function} callback 回调函数
 */
https.createServer(options,function(req,res){
    res.writeHead(200);
    res.end('Hello world!\n');
}).listen(3000);


// 创建一个安全的web请求服务

/**
 * 说明:一下为可选参数
 * host:域名或IP地址的服务器发出请求.默认是 'localhost'.
 * hostname: 支持 url.parse() hostname是首选的主机
 * port: 服务器远程端口.默认:443.
 * method: HTTP请求的方法字符串描述. 默认:'GET'.
 * path:请求路径,默认: '/'. 应该包括任何query字符串. E.G. '/index.html?page=12'
 * headers: 包含请求的头对象.
 * auth: 基本身份验证 i.e. 'user:password' to compute an Authorization header.
 * agent: 控制代理行为. 代理用于请求连接的默认connection是: keep-alive. 可能值有:
         undefined (default): 使用 globalAgent 的host和port.
         Agent object: 通过显示代理.
         false:代理连接池, 默认 Connection: close.[翻译有点问题]
 * @type {{hostname: string, port: number, path: string, method: string}}
 */
var options = {
    hostname:'encrypted.google.com',
    port:443,
    path:'/',
    method:'GET'
};
var req = https.request(options,function(res){
    console.log('statusCode: ',res.statusCode);
    console.log('headers: ',res.headers);

    res.on('data',function(d){
        process.stdout.write(d);
    });
});

req.end();
req.on('error',function(e){
    console.error(e);
})


转载于:https://my.oschina.net/antianlu/blog/261739

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值