Skip to content
0

node:http2

通常和 https 关联在一起

创建一个本地的 https 服务

使用 openssl 创建 cert 证书和 private key 文件:

$ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
  -keyout localhost-privkey.pem -out localhost-cert.pem

创建 http2 server 并执行 node server.js 启动:

import http2 from 'node:http2'
import fs from 'node:fs'

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem'),
})
server.on('error', err => console.error(err))

server.on('stream', (stream, headers) => {
  // stream is a Duplex
  stream.respond({
    'content-type': 'text/html; charset=utf-8',
    ':status': 200,
  })
  stream.end('<h1>Hello World</h1>')
})

server.listen(8443)

然后创建客户端连接,传入相同的 cert 证书:

import http2 from 'node:http2'
import fs from 'node:fs'

const client = http2.connect('https://localhost:8443', {
  ca: fs.readFileSync('localhost-cert.pem'),
})
client.on('error', err => console.error(err))

const req = client.request({ ':path': '/' })

req.on('response', (headers, flags) => {
  for (const name in headers)
    console.log(`${name}: ${headers[name]}`)
})

req.setEncoding('utf8')
let data = ''
req.on('data', (chunk) => { data += chunk })
req.on('end', () => {
  console.log(`\n${data}`)
  client.close()
})
req.end()

输出:

$ node client.js 
:status: 200
content-type: text/html; charset=utf-8
date: Wed, 04 Sep 2024 15:57:42 GMT

<h1>Hello World</h1>

如果你想在浏览器里面访问,需要安装证书。可以使用 mkcert 工具快速自动安装根证书,然后生成 key 和 cert 文件

$ mkcert localhost

Released under the MIT License.