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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM