如何使用 nghttp2 解决 "empty response" 错误?

How can I solve the "empty response" error using nghttp2?

我正在使用 nghttp2_asio。我使用 ./configure --enable-asio-lib 编译了它。然后,我将 /usr/local/lib 添加到 /etc/ld.so.conf 文件。代码如下:

#include "bits/stdc++.h"
#include "nghttp2/asio_http2_server.h"

using namespace std;
using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;

int main(int argc, char **argv) {
  http2 srv;
  srv.num_threads(4);
  srv.handle("/", [](const request &req, const response &res) {
    cout << req.uri().path << endl;
    header_map headers;
    headers.emplace("content-type", header_value{ "text/html", false });
    res.write_head(200, headers);
    res.end(file_generator("index.html"));
  });
  boost::system::error_code ec;
  if (srv.listen_and_serve(ec, "localhost", "8080")) cerr << ec.message() << endl;
  return 0;
}

当我尝试在 http://localhost:8080 上打开浏览器(Chrome 或 Firefox)时,出现以下错误:

This page isn't working

localhost didn't send any data.

ERR_EMPTY_RESPONSE

即使我尝试使用 curl,它也会给我错误:

curl: (52) Empty reply from server

唯一有效的是 curl http://localhost:8080 --http2-prior-knowledge

有解决办法吗?

您的浏览器似乎拒绝通过未加密的连接执行 HTTP/2。维基百科页面有 the following to say:

Although the standard itself does not require usage of encryption,[51] all major client implementations (Firefox,[52] Chrome, Safari, Opera, IE, Edge) have stated that they will only support HTTP/2 over TLS, which makes encryption de facto mandatory.[53]

cURL 有一个不同的问题:它默认为 HTTP/1,而您的 HTTP/2 服务器无法理解。添加标志使其直接使用 HTTP/2 二进制协议。或者,连接到 HTTPS 端点将自动打开 HTTP/2.

有关如何使用 加密服务 的示例,请参阅 the libnghttp2_asio documentation

int main(int argc, char *argv[]) {
  boost::system::error_code ec;
  boost::asio::ssl::context tls(boost::asio::ssl::context::sslv23);

  tls.use_private_key_file("server.key", boost::asio::ssl::context::pem);
  tls.use_certificate_chain_file("server.crt");

  configure_tls_context_easy(ec, tls);

  http2 server;

  // add server handlers here

  if (server.listen_and_serve(ec, tls, "localhost", "3000")) {
    std::cerr << "error: " << ec.message() << std::endl;
  }
}