兼容性接口


【Compatibility API】

兼容性 API 的目标是在使用 HTTP/2 时提供类似于 HTTP/1 的开发者体验,使得开发支持 HTTP/1 和 HTTP/2 的应用成为可能。该 API 仅针对 HTTP/1公共 API。然而,许多模块使用内部方法或状态,而这些不受支持,因为它是完全不同的实现。

【The Compatibility API has the goal of providing a similar developer experience of HTTP/1 when using HTTP/2, making it possible to develop applications that support both HTTP/1 and HTTP/2. This API targets only the public API of the HTTP/1. However many modules use internal methods or state, and those are not supported as it is a completely different implementation.】

以下示例使用兼容性 API 创建一个 HTTP/2 服务器:

【The following example creates an HTTP/2 server using the compatibility API:】

import { createServer } from 'node:http2';
const server = createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('ok');
});const http2 = require('node:http2');
const server = http2.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('ok');
});

要创建混合 HTTPS 和 HTTP/2 服务器,请参考 ALPN 协商 部分。 不支持从非 TLS 的 HTTP/1 服务器升级。

【In order to create a mixed HTTPS and HTTP/2 server, refer to the ALPN negotiation section. Upgrading from non-tls HTTP/1 servers is not supported.】

HTTP/2 兼容性 API 由 Http2ServerRequestHttp2ServerResponse 组成。它们旨在与 HTTP/1 保持 API 兼容,但并不隐藏协议之间的差异。例如,HTTP 状态码的状态消息会被忽略。

【The HTTP/2 compatibility API is composed of Http2ServerRequest and Http2ServerResponse. They aim at API compatibility with HTTP/1, but they do not hide the differences between the protocols. As an example, the status message for HTTP codes is ignored.】