兼容性接口


¥Compatibility API

Compatibility 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.