您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Node中怎么啟動(dòng)https服務(wù)器,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
首先你需要生成https證書,可以去付費(fèi)的網(wǎng)站購買或者找一些免費(fèi)的網(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ù)項(xiàng)目的路徑導(dǎo)入生成的證書文件 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服務(wù)器實(shí)例 const httpsServer = https.createServer(credentials, async (req, res) => { res.writeHead(200) res.end('Hello World!') }) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動(dòng)服務(wù)器,監(jiān)聽對應(yīng)的端口 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ù)項(xiàng)目的路徑導(dǎo)入生成的證書文件 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實(shí)例 const app = express() // 處理請求 app.get('/', async (req, res) => { res.status(200).send('Hello World!') }) // 創(chuàng)建https服務(wù)器實(shí)例 const httpsServer = https.createServer(credentials, app) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動(dòng)服務(wù)器,監(jiān)聽對應(yīng)的端口 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ù)項(xiàng)目的路徑導(dǎo)入生成的證書文件 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實(shí)例 const app = koa() // 處理請求 app.use(async ctx => { ctx.body = 'Hello World!' }) // 創(chuàng)建https服務(wù)器實(shí)例 const httpsServer = https.createServer(credentials, app.callback()) // 設(shè)置https的訪問端口號 const SSLPORT = 443 // 啟動(dòng)服務(wù)器,監(jiān)聽對應(yīng)的端口 httpsServer.listen(SSLPORT, () => { console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`) })
關(guān)于Node中怎么啟動(dòng)https服務(wù)器就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。