在还没真正部署 Express 应用的时候,我们希望先在本地将 HTTPS 跑起来。下面就来实现一下本地创建 HTTPS 服务器吧。
HTTPS 证书
在还没买 HTTPS 证书前,我们可以先创建我们自己签发的 HTTPS 证书做测试。跑下面的命令。
openssl req -nodes -new -x509 -keyout server.key -out server.cert
然后就会生成下面两个文件。

HTTPS 服务器
原来,我们是使用 http 这个包的,现在只要换成 https 包就可以了,还要将上面这两个文件的内容放到 server 里。
const express = require('express')
const fs = require('fs')
const https = require('https')
const app = express()
app.get('/', function (req, res) {
res.send('hello world')
})
const key = fs.readFileSync('../keys/server.key')
const cert = fs.readFileSync('../keys/server.cert')
const credentials = {key, cert}
https.createServer(credentials, app)
.listen(4000, function () {
console.log('Example app listening on port 4000! Go to https://localhost:4000/')
})
本地访问 HTTPS
写好上面的代码后,将服务器跑起来,会出现下面的警告。

因为这个证书不是 CA 颁发的,所以 Chrome 会觉得你是 Attack。这里的解决方法就是让 Chrome 允许你在 localhost 这个域名下使用自己颁发的证书即可。
在 URL 输入 chrome://flags/#allow-insecure-localhost,会看到下面的界面,然后将 Allow invalid certificates for resources loaded from localhost 这个选项 Enable 就可以了。

最后
当然这种方法只能用自己 issue 的证书,最佳的实践应该是使用 Nginx 来做反代。
网友评论