1. 安装node环境(自行谷歌百度,不赘述) 2. 安装express(自行谷歌百度,不赘述) 3. 打开命令行,利用openssl生成证书文件
1
2
3
4
5
6
7
8
//生成私钥key文件
openssl genrsa 1024 > /keys/private.pem

//通过私钥文件生成CSR证书签名
openssl req - new - key / keys / private.pem - out / keys / csr.pem

//通过私钥文件和CSR证书签名生成证书文件
openssl x509 - req - days 365 - in /keys/csr.pem - signkey / keys / private.pem - out / keys / file.crt
  1. 编写server文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');

//引入私钥、证书
var privateKey = fs.readFileSync('./keys/private.pem', 'utf8');
var certificate = fs.readFileSync('./keys/file.crt', 'utf8');
var credentials = {
key: privateKey,
cert: certificate
};

//创建服务,设置端口号
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 18080;
var SSLPORT = 18081;

//监听端口号
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});

//路由
app.get('/', function(req, res) {
if (req.protocol === 'https') {
res.status(200).send('这是一个经过加密的https请求!');
} else {
res.status(200).send('这是一个普通的http请求!');
}
});
  1. 启动服务
1
node server.js