您的位置:首页 > 理论基础 > 计算机网络

Node.js https.server API解析

2014-05-07 16:51 495 查看
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);
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: