Nodejs+Express创建HTTPS服务器

reference:
https://www.jianshu.com/p/6406584ef018
https://www.cnblogs.com/handongyu/p/6260209.html
https://blog.csdn.net/CHENYUFENG1991/article/details/60340006
Set up Https server based on node. js Express:
https://blog.csdn.net/xingyanchao/article/details/79362443

step 1:
Install Install the nodejs tool ,  Install the express tool 
step 2:
Generate the secret key file:
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
step 3:
Execute the command:
express HttpsService   // Generate the folder HttpsService, Automatically generate project folders
cd   HttpsService 
mkdir certificate
copy private.pem csr.pem file.crt to the folder certificate
edit app.js:/
var express = require('express'); //  the project server USES the express framework
var app = express();
var path = require('path');
var fs = require('fs');
//Use the HTTP and HTTPS modules that come with nodejs
var http = require('http');
var https = require('https');
//Import the generated certificate file according to the project path
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);
// You can set the access port Numbers for HTTP and HTTPS, respectively
var PORT = 8000;
var SSLPORT = 8001;
// Create HTTP server
httpServer.listen(PORT, function() {
    console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
//Create HTTPS server
httpsServer.listen(SSLPORT, function() {
    console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});
//You can tell if it's HTTP or HTTPS based on the request
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!');
    }
});
//

step 4: start server

node app.js

http access: http://IP:8000  https access:  https://IP:8001

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值