HTTP2
HTTP2
Fastify 支持通过 HTTPS (h2) 或纯文本 (h2c) 使用 HTTP2。
目前,Fastify 无法通过任何特定于 HTTP2 的 API 使用,但 Node 的 req
和 res
可以通过我们的 Request
和 Reply
接口访问。欢迎提交 PR。
安全连接 (HTTPS)
所有现代浏览器仅在安全连接上支持 HTTP2。
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')({
http2: true,
https: {
key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
}
})
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
ALPN 协商 允许在同一套接字上同时支持 HTTPS 和 HTTP/2。Node 核心 req
和 res
对象可以是 HTTP/1 或 HTTP/2。Fastify 原生支持此功能。
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')({
http2: true,
https: {
allowHTTP1: true, // fallback support for HTTP1
key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
}
})
// this route can be accessed through both protocols
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
您可以使用以下命令测试您的新服务器:
$ npx h2url https://localhost:3000
纯文本或不安全连接
如果您正在构建微服务,则可以以纯文本方式连接到 HTTP2,但是浏览器不支持这种方式。
'use strict'
const fastify = require('fastify')({
http2: true
})
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
您可以使用以下命令测试您的新服务器:
$ npx h2url http://localhost:3000