HTTP2
Fastify 支持通过 HTTPS (h2) 或纯文本 (h2c) 的 HTTP2。
目前,没有提供任何特定于 HTTP2 的 API 供 Fastify 使用,但可以通过 Request
和 Reply
接口访问 Node 的 req
和 res
对象。欢迎提交 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, // HTTP1 的回退支持
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 })
使用以下命令测试新服务器:
$ 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