1.7 KiB
1.7 KiB
title, id, categories, tags, date
| title | id | categories | tags | date | ||||
|---|---|---|---|---|---|---|---|---|
| 用Node+express搭建本地https服务 | 90 |
|
|
2017-01-24 15:21:05 |
- 安装node环境(自行谷歌百度,不赘述) 2. 安装express(自行谷歌百度,不赘述) 3. 打开命令行,利用openssl生成证书文件
//生成私钥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
- 编写server文件
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请求!');
}
});
- 启动服务
node server.js