如何使用 node.js 发送 HTTP/2.0 请求

Posted

技术标签:

【中文标题】如何使用 node.js 发送 HTTP/2.0 请求【英文标题】:How to send a HTTP/2.0 request with node.js 【发布时间】:2020-01-29 02:10:18 【问题描述】:

如何在 nodejs 中发送 httpVersion 2.0 请求?

几乎所有的请求模块我都试过了,都是httpVersion 1.1

【问题讨论】:

内置有什么问题? nodejs.org/api/http2.html 示例代码可以在node.js核心文档中找到:nodejs.org/api/http2.html#http2_client_side_example 【参考方案1】:

由于Node.js 8.4.0,您可以使用内置的http2 module 来实现http2 服务器。或者,如果你想在 Express 中使用 http2,这里有一个很棒的 npm 模块:spdy。

这是来自express-spdy的一些代码:

const fs = require('fs');
const path = require('path');
const express = require('express');
const spdy = require('spdy');

const CERTS_ROOT = '../../certs/';

const app = express();

app.use(express.static('static'));

const config = 
    cert: fs.readFileSync(path.resolve(CERTS_ROOT, 'server.crt')),
    key: fs.readFileSync(path.resolve(CERTS_ROOT, 'server.key')),
;

spdy.createServer(config, app).listen(3000, (err) => 
    if (err) 
        console.error('An error occured', error);
        return;
    

    console.log('Server listening on https://localhost:3000.')
);

【讨论】:

第一句话是正确的,但其余的答案与问题无关。他正在寻找一个 http2 客户端,而不是服务器 我不是在寻找 HTTP/2.0 服务器。我正在寻找一种向 google.com 发送 HTTP/2.0 请求的方法【参考方案2】:

获取请求

const http2 = require("http2");
const client = http2.connect("https://www.google.com");

const req = client.request(
 ":path": "/"
);

let data = "";

req.on("response", (headers, flags) => 
 for (const name in headers) 
  console.log(`$name: $headers[name]`);
 

);

req.on("data", chunk => 
 data += chunk;
);
req.on("end", () => 
 console.log(data);
 client.close();
);
req.end();

POST 请求

     let res = "";
      let postbody = JSON.stringify(
       key: value
      );
      let baseurl = 'baseurl'
      let path = '/any-path'
      const client = http2.connect(baseurl);
      const req = client.request(
       ":method": "POST",
       ":path": path,
       "content-type": "application/json",
       "content-length": Buffer.byteLength(postbody),
      );


      req.on("response", (headers, flags) => 
       for (const name in headers) 
        console.log(`$name: $headers[name]`);
       

      );
      req.on("data", chunk => 
       res = res + chunk;
      );
      req.on("end", () => 
       client.close();
      );

   req.end(postbody)

更多详情请看官方文档: https://nodejs.org/api/http2.html#http2_client_side_example

【讨论】:

我怎样才能收到所有的标题? 好答案。您可能需要将内容类型标头更改为 application/x-www-form-urlencoded,或者您需要的任何内容,具体取决于后端。重要的是内容长度和 req.end 以及要发送的正文/数据。另一方面,您可能需要通过 set-cookie 标头在“响应”回调中手动添加 cookie 支持。

以上是关于如何使用 node.js 发送 HTTP/2.0 请求的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Visual C# 中发送 HTTP 2.0 请求

如何使用 Node.js 通过代理发送 HTTP/2 请求?

如何使用 Node.js 将 JSON 数据从 Node.js 发送和获取到 HTML

如何使用 node.js 发送“FIN”?

如何使用 Fetch 在前端显示通过 HTTP (Node.js) 发送的图像?

如何通过 ajax 调用将 html 表单数据发送到 node.js 服务器?