nodejs的express框架创建https服务器

本文详细介绍如何在Windows环境下使用openssl生成HTTPS私钥和证书,安装及使用Express框架,并创建HTTPS服务器。涵盖从openssl的下载、安装到生成私钥、证书,再到Express框架的全局安装和本地项目使用,最后实现HTTPS服务器的搭建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 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.youkuaiyun.com/gengxiaoming7/article/details/78505107

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

https://blog.youkuaiyun.com/mlsama/article/details/8021103

转载于:https://www.cnblogs.com/ihzeng/p/10447652.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值