跳至主要內容
版本:最新版本 (v5.0.x)

HTTP2

HTTP2

Fastify 支援透過 HTTPS (h2) 或純文字 (h2c) 的 HTTP2。

目前,沒有任何 HTTP2 特定的 API 可透過 Fastify 使用,但可以透過我們的 RequestReply 介面存取 Node 的 reqres。歡迎提交 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 協商允許在同一個 socket 上支援 HTTPS 和 HTTP/2。Node 核心的 reqres 物件可以是 HTTP/1HTTP/2Fastify 開箱即用即可支援此功能

'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://127.0.0.1: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 https://127.0.0.1:3000