社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
在nodejs中使用express来搭建框架可以说是非常的简单方便,但是一般默认创建的都是http服务器,也就是只能通过http协议进行访问。如今https已经是发展趋势,我们应该顺应时代的潮流。在本篇文章中,我们将会来使用自签名的方式创建证书,然后使用express框架来搭建https服务器,最后让浏览器或者客户端使用https协议进行访问。
首先我们要生成证书文件:
(1)生成私钥key文件(下面的pathway表示你要保存的文件路径位置)
openssl genrsa 1024 > /pathway/private.pem
openssl req -new -key /pathway/private.pem -out csr.pem
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!');
}
});
http访问:
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/chenyufeng1991/article/details/60340006
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!