Node 시작 https 서버

2673 단어
우선 https 인증서를 생성해야 합니다. 비용을 지불하는 사이트에서 구매하거나 무료 사이트를 찾을 수 있습니다. 키나crt나pem가 끝날 수도 있습니다.OpenSSL을 통해 서로 다른 형식 간에 변환할 수 있습니다.
openssl x509 -in mycert.crt -out mycert.pem -outform PEM

Node 네이티브 버전:

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}`)
})

express 버전

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}`)
})

koa 버전

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}`)
})


블로그에 오신 것을 환영합니다.

좋은 웹페이지 즐겨찾기