如何在Node.js中发送HTTP版本2.0的请求?
我已经尝试了几乎所有可用的请求模块,但它们都是HTTP版本1.1。
GET 请求:
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
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时针对具有多个请求的同一端点的主要考虑点
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();