NodeJS + express 添加HTTPS支持

1. 生成自签名证书文件:

openssl req -nodes -new -x509 -keyout server.key -out server.cert

2. 在Express开启HTTPS支持, 添加一下类似代码:

var express = require('express')
var fs = require('fs')
var https = require('https')
var app = express()

app.get('/', function (req, res) {
  res.send('hello world')
})

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app)
.listen(3000, function () {
  console.log('Example app listening on port 3000! Go to https://localhost:3000/')
})

server.key, server.cert放到express项目目录下。
现在执行npm start运行服务器,在浏览器中输入地址: https://localhost:3000 就能访问本地的https服务器了。
HTTP服务的默认端口为80, 而HTTPS默认端口为443,  如果想https://locahost 访问本地的https服务,那么将HTTPS的端口设置为默认端口443即可。

Reference: https://timonweb.com/javascript/running-expressjs-server-over-https/

posted @ 2020-10-18 15:08  opencoder  阅读(1855)  评论(0编辑  收藏  举报