ホームページ  >  記事  >  ウェブフロントエンド  >  Nodeでhttpsサーバーを起動する方法

Nodeでhttpsサーバーを起動する方法

php中世界最好的语言
php中世界最好的语言オリジナル
2018-03-19 14:42:492104ブラウズ

今回はNodeでhttpsサーバーを起動する方法を紹介します。 Nodeでhttpsサーバーを起動する際の注意点は何ですか?

まず、https 証明書を生成する必要があります。有料の Web サイトから購入するか、キー、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}`)
})

この記事の事例を読んだ後は、この方法を習得したと思います。 、オンラインのphp中国語のその他の関連記事に注意してください。

推奨読書:

イベントモデルの詳しい説明

イベントループの使用方法

以上がNodeでhttpsサーバーを起動する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。