Fastify 中文文档 (latest — v4.26.1)

HTTP2

Fastify 提供了从 Node 8.8.0 开始的对 HTTP2 实验性支持Fastify 支持 HTTPS 和普通文本的 HTTP2 支持。需要注意的是,Node 8.8.1 以上的版本才支持 HTTP2。

当前没有任何 HTTP2 相关的 APIs 是可用的,但 Node reqres 可以通过 RequestReply 接口访问。欢迎相关的 PR。

安全 (HTTPS)

所有的现代浏览器都只能通过安全的连接 支持 HTTP2:

'use strict'

const fs = require('fs')
const path = require('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(3000)

ALPN 协商允许在同一个 socket 上支持 HTTPS 和 HTTP/2。 Node 核心 reqres 对象可以是 HTTP/1 或者 HTTP/2Fastify 自带支持开箱即用:

'use strict'

const fs = require('fs')
const path = require('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'))
  }
})

// 该路由从 HTTPS 与 HTTP2 均可访问
fastify.get('/', function (request, reply) {
  reply.code(200).send({ hello: 'world' })
})

fastify.listen(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(3000)

你可以像这样测试你的新服务器:

$ npx h2url http://localhost:3000