兼容的 API


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

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

const http2 = require('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 服务器升级。

HTTP/2 兼容性 API 由 Http2ServerRequestHttp2ServerResponse 组成。 其目标是与 HTTP/1 的 API 兼容,但其并没有隐藏协议之间的差异。 例如,HTTP 代码的状态消息被忽略。

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.

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

const http2 = require('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');
});

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.

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.