NodeJS配置https服務並實現靜態資源的訪問
一.准備工作
在實現如題所示的功能之前,需要做的事情是安裝NodeJS,至於如何安裝並不是本文所要講解的內容,大家可以自行百度查詢;另外一個事情就是需要申請證書,可以在騰訊雲上申請免費證書。前兩項工作筆者已經都做准備完畢,如果有需要幫助可留言咨詢。那么我們就開始切入主題。
二.配置服務器
A.執行如下命令安裝express
npm i express --save
B.項目結構如下圖所示:
C.index.html文件內容如下(該文件並沒有實際的價值,主要為了演示靜態資源):
<html lang="en"> <head> <meta charset="UTF-8"> <title>測試文件</title> <script src="public/js/jquery-3.3.1.min.js"></script> <script> $(function() { $("#name").html('正井貓') }) </script> </head> <body> <img src="public/images/cat.jpg"> <span id="name"></span> </body> </html>
D.server.js文件內容如下:
const https = require('https') const fs = require('fs') const express = require('express') const app = express() //配置證書位置 const options = { key: fs.readFileSync(__dirname + '/ca/2_zenithcat.com.key'), cert: fs.readFileSync(__dirname + '/ca/1_zenithcat.com_bundle.crt') } https.createServer(options, app).listen(443) //配置靜態資源的訪問路徑,對應到public這個目錄下,如果還有其他目錄,按照該規則添加即可 app.use('/public', express.static("public")) app.get('/', (request, response) => { response.writeHead(200) fs.createReadStream(__dirname + "/index.html") .pipe(response) })
E.在 C:\Windows\System32\drivers\etc\hosts 文件中增加如下內容:
127.0.0.1 zenithcat.com
F.啟動服務器:
node server.js
G.訪問頁面