首先你須要生成https證書,能夠去付費的網站購買或者找一些免費的網站,可能會是key或者crt或者pem結尾的。不一樣格式之間能夠經過OpenSSL轉換,如:express
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
const https = require('https') const path = require('path') const fs = require('fs') // 根據項目的路徑導入生成的證書文件 const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8') const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8') const credentials = { key: privateKey, cert: certificate, } // 建立https服務器實例 const httpsServer = https.createServer(credentials, async (req, res) => { res.writeHead(200) res.end('Hello World!') }) // 設置https的訪問端口號 const SSLPORT = 443 // 啓動服務器,監聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
const express = require('express') const path = require('path') const fs = require('fs') const https = require('https') // 根據項目的路徑導入生成的證書文件 const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8') const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8') const credentials = { key: privateKey, cert: certificate, } // 建立express實例 const app = express() // 處理請求 app.get('/', async (req, res) => { res.status(200).send('Hello World!') }) // 建立https服務器實例 const httpsServer = https.createServer(credentials, app) // 設置https的訪問端口號 const SSLPORT = 443 // 啓動服務器,監聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
const koa = require('koa') const path = require('path') const fs = require('fs') const https = require('https') // 根據項目的路徑導入生成的證書文件 const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8') const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8') const credentials = { key: privateKey, cert: certificate, } // 建立koa實例 const app = koa() // 處理請求 app.use(async ctx => { ctx.body = 'Hello World!' }) // 建立https服務器實例 const httpsServer = https.createServer(credentials, app.callback()) // 設置https的訪問端口號 const SSLPORT = 443 // 啓動服務器,監聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })