nodejs的express框架创建https服务器

一 openssl创建https私钥和证书

1.下载windows版openssl:

http://slproweb.com/products/Win32OpenSSL.html

Win64OpenSSL_Light-1_1_1b.exe

2.安装并使用openssl:

2.1 正常安装openssl.exe

2.2 进入openssl安装目录的bin里面

#生成私钥key文件

openssl genrsa 1024 > ./private.pem

#通过私钥文件生成CSR证书签名

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

#通过私钥文件和CSR证书签名生成证书文件

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

二 windows下安装和使用express框架:

1.全局安装express框架,cmd打开命令行,输入如下命令:

npm install -g express

express 4.x版本中将命令工具分出来,安装一个命令工具,执行命令:

npm install -g express-generator

输入express --version验证

2.如果在执行js文件仍报Error: Cannot find module express错误。

解决办法:
    在自己的工程目录下再次执行:
        npm install express

三 创建https服务器

1.进入node项目下,拷贝私钥和证书到此目录下

2.创建node服务程序https.js:

var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('./private.pem', 'utf8');
var certificate = fs.readFileSync('./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);
}); // Welcome
app.get('/', function(req, res) {
if(req.protocol === 'https') {
res.status(200).send('Welcome to Safety Land!');
}
else {
res.status(200).send('Welcome!');
}
});

3.运行:node https.js

4.浏览器访问:https://localhost:18081/

参考:
https://blog.csdn.net/gengxiaoming7/article/details/78505107

https://www.cnblogs.com/handongyu/p/6260209.html

https://blog.csdn.net/mlsama/article/details/8021103

上一篇:ERROR 1227 (42000): Access denied; you need (at least one of) the PROCESS privilege(s) for this oper


下一篇:[boostrap]debian下为arm创建debian和emdebian文件系统