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

fiei3ece  于 2023-01-25  发布在  Node.js
关注(0)|答案(3)|浏览(494)

如何在nodejs中发送httpVersion 2.0请求?
我已经尝试了几乎所有的请求模块,它们都是httpVersion 1.1

1dkrff03

1dkrff031#

获取请求

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

yptwkmov

yptwkmov2#

从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.')
});
ctehm74n

ctehm74n3#

只是为了增加更多的注意,因为这是使用HTTP2的主要原因,如果您有多个请求到同一个端点

var payload1 = JSON.stringify({});
var payload2 = JSON.stringify({});

const client = http2.connect('server url');
const request = client.request({
  ":method": "POST",
  ':path': 'some path',
  'authorization': `bearer ${token}`,
  "content-type": "application/json",
});

request.on('response', (headers, flags) => {
  for (const name in headers) {
    console.log(`${name}: ${headers[name]}`);
  }
});
request.setEncoding('utf8');
let data = ''
request.on('data', (chunk) => { data += chunk; });
request.on('end', () => {
  console.log(`\n${data}`);
  client.close();
});
// send as many request you want and then close the connection
request.write(payload1)
request.write(payload2)
request.end();

希望能帮到人

相关问题