在 NodeJS 中执行传出 HTTP2 请求
Performing outgoing HTTP2 requests in NodeJS
我检查了 NodeJS documentation 但找不到任何关于如何使以下代码使用 HTTP2 执行请求的信息:
const https = require('https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end()
难道连最新版本的 NodeJS 都还不支持吗?
这在 v9.9.0
中可用。您可以查看 HTTP2 in Nodejs. You can create a secureServer in HTTP2 if you want the whole thing. Else firing off requests using http2 is available too. You can take a look at this article 以获得一些想法
您找不到 Node.js 本地方式来:
how to make the following code use HTTP2 to carry out the request
因为,HTTP2 的工作原理与 HTTP1.1 完全不同。
因此,Node.jshttp2核心模块导出的接口完全不同,多了多路复用等特性
要使用 HTTP1.1 接口发出 HTTP2 请求,您可以使用 npm 模块,我个人编码并使用:
http2-client
const {request} = require('http2-client');
const h1Target = 'http://www.example.com/';
const h2Target = 'https://www.example.com/';
const req1 = request(h1Target, (res)=>{
console.log(`
Url : ${h1Target}
Status : ${res.statusCode}
HttpVersion : ${res.httpVersion}
`);
});
req1.end();
const req2 = request(h2Target, (res)=>{
console.log(`
Url : ${h2Target}
Status : ${res.statusCode}
HttpVersion : ${res.httpVersion}
`);
});
req2.end();
我检查了 NodeJS documentation 但找不到任何关于如何使以下代码使用 HTTP2 执行请求的信息:
const https = require('https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end()
难道连最新版本的 NodeJS 都还不支持吗?
这在 v9.9.0
中可用。您可以查看 HTTP2 in Nodejs. You can create a secureServer in HTTP2 if you want the whole thing. Else firing off requests using http2 is available too. You can take a look at this article 以获得一些想法
您找不到 Node.js 本地方式来:
how to make the following code use HTTP2 to carry out the request
因为,HTTP2 的工作原理与 HTTP1.1 完全不同。 因此,Node.jshttp2核心模块导出的接口完全不同,多了多路复用等特性
要使用 HTTP1.1 接口发出 HTTP2 请求,您可以使用 npm 模块,我个人编码并使用: http2-client
const {request} = require('http2-client');
const h1Target = 'http://www.example.com/';
const h2Target = 'https://www.example.com/';
const req1 = request(h1Target, (res)=>{
console.log(`
Url : ${h1Target}
Status : ${res.statusCode}
HttpVersion : ${res.httpVersion}
`);
});
req1.end();
const req2 = request(h2Target, (res)=>{
console.log(`
Url : ${h2Target}
Status : ${res.statusCode}
HttpVersion : ${res.httpVersion}
`);
});
req2.end();