Skip to main content

HTTP2

HTTP2

Fastify 支持基于 HTTPS (h2) 或纯文本 (h2c) 的 HTTP2。

¥Fastify supports HTTP2 over either HTTPS (h2) or plaintext (h2c).

目前,Fastify 无法提供任何 HTTP2 特定的 API,但可以通过我们的 RequestReply 接口访问 Node 的 reqres。欢迎 PR。

¥Currently, none of the HTTP2-specific APIs are available through Fastify, but Node's req and res can be accessed through our Request and Reply interface. PRs are welcome.

安全(HTTPS)

¥Secure (HTTPS)

HTTP2 在所有现代浏览器中仅通过安全连接受支持:

¥HTTP2 is supported in all modern browsers only over a secure connection:

'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 核心 reqres 对象可以是 HTTP/1HTTP/2。Fastify 开箱即用地支持这一点:

¥ALPN negotiation allows support for both HTTPS and HTTP/2 over the same socket. Node core req and res objects can be either HTTP/1 or HTTP/2. Fastify supports this out of the box:

'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 })

你可以使用以下方法测试你的新服务器:

¥You can test your new server with:

$ npx h2url https://localhost:3000

空白或不安全

¥Plain or insecure

如果你正在构建微服务,则可以以纯文本方式连接到 HTTP2,但是浏览器不支持此功能。

¥If you are building microservices, you can connect to HTTP2 in plain text, however, this is not supported by browsers.

'use strict'

const fastify = require('fastify')({
http2: true
})

fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})

fastify.listen({ port: 3000 })

你可以使用以下方法测试你的新服务器:

¥You can test your new server with:

$ npx h2url http://localhost:3000