nodejs express配置自签名https服务器的方法

2020-06-17 06:51:56易采站长站整理

在nodejs中使用express来搭建框架可以说是非常的简单方便,但是一般默认创建的都是http服务器,也就是只能通过http协议进行访问。如今https已经是发展趋势,我们应该顺应时代的潮流。在本篇文章中,我们将会来使用自签名的方式创建证书,然后使用express框架来搭建https服务器,最后让浏览器或者客户端使用https协议进行访问。

首先我们要生成证书文件:

(1)生成私钥key文件(下面的pathway表示你要保存的文件路径位置)
 


openssl genrsa 1024 > /pathway/private.pem

(2)通过上面生成的私钥文件生成CSR证书签名


openssl req -new -key /pathway/private.pem -out csr.pem

(3)通过上述私钥文件和CSR证书签名生成证书文件

openssl x509 -req -days 365 -in csr.pem -signkey /pathway/private.pem -out /pathway/file.crt 

此时生成的三个文件如下:

此时把这三个文件拷贝到你的nodejs项目目录下,比如我直接在项目根目录下新建certificate文件夹,然后放入三个文件:

 完成以上步骤后,修改项目的启动文件,我这里的启动文件是app.js,或者有人是server.js,以下代码实现都一样:


var express = require('express'); // 项目服务端使用express框架
var app = express();
var path = require('path');
var fs = require('fs');

//使用nodejs自带的http、https模块
var http = require('http');
var https = require('https');

//根据项目的路径导入生成的证书文件
var privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.pem'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, './certificate/file.crt'), 'utf8');
var credentials = {key: privateKey, cert: certificate};

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

//可以分别设置http、https的访问端口号
var PORT = 8000;
var SSLPORT = 8001;

//创建http服务器
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});

//创建https服务器
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});

//可以根据请求判断是http还是https
app.get('/', function (req, res) {
if(req.protocol === 'https') {
res.status(200).send('This is https visit!');
}
else {
res.status(200).send('This is http visit!');
}
});

代码实现完成后,启动app.js脚本,可以使用”node app.js”命令来启动,或者在其他IDE中run, 然后在浏览器中访问(注意express不是系统内置模块,需要通过npm安装):