Node啟動https服務器的教程
更新時間:2018年03月18日 14:18:43 作者:任乃千
這篇文章主要介紹了Node啟動https服務器的教程,有node原生版本,express 版本,koa版本,具體各個版本的代碼講解大家參考下本文
首先你需要生成https證書,可以去付費的網(wǎng)站購買或者找一些免費的網(wǎng)站,可能會是key或者crt或者pem結(jié)尾的。不同格式之間可以通過OpenSSL轉(zhuǎn)換,如:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
Node原生版本:
const https = require('https') const path = require('path') const fs = require('fs') // 根據(jù)項目的路徑導入生成的證書文件 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, } // 創(chuàng)建https服務器實例 const httpsServer = https.createServer(credentials, async (req, res) => { res.writeHead(200) res.end('Hello World!') }) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動服務器,監(jiān)聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
express版本
const express = require('express') const path = require('path') const fs = require('fs') const https = require('https') // 根據(jù)項目的路徑導入生成的證書文件 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, } // 創(chuàng)建express實例 const app = express() // 處理請求 app.get('/', async (req, res) => { res.status(200).send('Hello World!') }) // 創(chuàng)建https服務器實例 const httpsServer = https.createServer(credentials, app) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動服務器,監(jiān)聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
koa版本
const koa = require('koa') const path = require('path') const fs = require('fs') const https = require('https') // 根據(jù)項目的路徑導入生成的證書文件 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, } // 創(chuàng)建koa實例 const app = koa() // 處理請求 app.use(async ctx => { ctx.body = 'Hello World!' }) // 創(chuàng)建https服務器實例 const httpsServer = https.createServer(credentials, app.callback()) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動服務器,監(jiān)聽對應的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
總結(jié)
以上所述是小編給大家介紹的Node啟動https服務器的教程,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
相關(guān)文章
服務器常用磁盤陣列RAID原理、種類及性能優(yōu)缺點對比
這篇文章主要介紹了磁盤陣列RAID原理、種類及性能優(yōu)缺點對比,根據(jù)硬件與硬盤數(shù)量選擇適合自己的磁盤陣列很重要,需要的朋友可以參考下2018-05-05Win2003下cwRsyncServer服務端與cwRsync客戶端數(shù)據(jù)同步實例教程
這篇文章主要介紹了Win2003下cwRsyncServer服務端與cwRsync客戶端數(shù)據(jù)同步實例教程,需要的朋友可以參考下2015-07-07