简单示例
//steps-01:建服务器
//http-server.js
var http = require('http');
var server = http.createServer(function(serverReq, serverRes){
var url = serverReq.url;
serverRes.end( '您访问的地址是:' + url );
});
server.listen(3000);
//steps-02:启服务器
node http-server.js
//steps-03:建客户端
//http-client.js
var http = require('http');
var client = http.get('http://127.0.0.1:3000', function(clientRes){
clientRes.pipe(process.stdout);
});
//steps-04:启客户端
node http-client.js
安全证书
//创建目录
mkdir cert
//切换目录
cd cert
//生成私钥
openssl genrsa -out chyingp-key.pem 2048
//证书签名
openssl req -new \
-sha256
-key chyingp-key.key.pem \
-out chyingp-csr.pem \
-subj "/C=CN/ST=Guandong/L=Shenzhen/O=YH Inc/CN=www.chyingp.com"
生成证书
openssl x509 \
-req -in chyingp-csr.pem \
-signkey chyingp-key.pem \
-out chyingp-cert.pem
安全连接
//steps-01:建服务器
//https-server.js
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('./cert/chyingp-key.pem'), // 私钥
cert: fs.readFileSync('./cert/chyingp-cert.pem') // 证书
};
var server = https.createServer(options, function(req, res){
res.end('这是来自HTTPS服务器的返回');
});
server.listen(3000);
//steps-02:本地域名
127.0.0.1 www.chyingp.com
//steps-03:启服务器
node https-server.js
//steps-04:建客户端
//https-client.js
var https = require('https');
https.get('https://www.baidu.com', function(res){
console.log('status code: ' + res.statusCode);
console.log('headers: ' + res.headers);
res.on('data', function(data){
process.stdout.write(data);
});
}).on('error', function(err){
console.error(err);
});
//steps-05:启客户端
node https-client.js
简单应用
/*******访问安全证书不受信任的网站,忽略安全警告,继续访问************/
//https-client.js
var https = require('https');
var fs = require('fs');
var options = {
hostname: 'kyfw.12306.cn',
path: '/otn/leftTicket/init',
rejectUnauthorized: false // 忽略安全警告
};
var req = https.get(options, function(res){
res.pipe(process.stdout);
});
req.on('error', function(err){
console.error(err.code);
});
/*******访问安全证书不受信任的网站,将CA加入受信列表************/
//steps-01:下载证书
//srca.cer
//steps-02:转换格式
openssl x509 -in srca.cer -inform der -outform pem -out srca.cer.pem
//steps-03:修改配置
//https-client.js
var https = require('https');
var fs = require('fs');
var ca = fs.readFileSync('./srca.cer.pem');
var options = {
hostname: 'kyfw.12306.cn',
path: '/otn/leftTicket/init',
ca: [ ca ]
};
var req = https.get(options, function(res){
res.pipe(process.stdout);
});
req.on('error', function(err){
console.error(err.code);
});
相关文档
http://www.cnblogs.com/chyingp/p/node-learning-guide-https.html
DER vs. CRT vs. CER vs. PEM Certificates and How To Convert Them
网友评论