使用 Express 在 localhost 上创建 HTTPS 服务器

1. 创建密钥和证书(终端)

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

2.获取解密密钥

openssl rsa -in keytmp.pem -out key.pem

获得密钥和证书后,我们需要将其包含在我们的服务器中并使用它启动 https 服务器。

3. 包括您的服务器的证书和密钥。

const fs = require('fs');
const key = fs.readFileSync('./key.pem');
const cert = fs.readFileSync('./cert.pem');

4. 使用 Express 创建 HTTPS 服务器

const express = require('express');
const https = require('https');
const app = express();
const server = https.createServer({key: key, cert: cert }, app);

就是这样。我们现在可以开始在我们的服务器上监听请求了。

5.开始监听请求

app.get('/', (req, res) => { res.send('this is an secure server') });
server.listen(443, () => { console.log('listening on 443') });
// HTTPS 端口默认443

6 访问 https://localhost 或者 https://127.0.0.1

这时浏览器会报错,是不安全的链接,使用safari 访问,添加证书信任可继续访问

7. 添加域名访问,例如: https://xyz.com

修改本级host:sudo vim /etc/hosts
添加: 
127.0.0.1   xyz.com

访问 https://xyz.com 这时浏览器继续报错,是不安全的链接,使用safari 访问,添加证书信任可继续访问

你可能感兴趣的:(使用 Express 在 localhost 上创建 HTTPS 服务器)