NodeJS中发起HTTP2出站请求的实现方法咨询
Got it, let's walk through converting your existing HTTPS request to use HTTP/2. Node.js has built-in support for HTTP/2 via the http2 module, and the transition is pretty straightforward once you wrap your head around HTTP/2's session-based model.
First, let's look at the modified code, then break down the key differences:
const http2 = require('http2'); // Establish an HTTP/2 session with the server const session = http2.connect('https://encrypted.google.com'); // Handle session-level errors (critical for debugging connection issues) session.on('error', (err) => console.error('Session error:', err)); // Create a request stream within the session const req = session.request({ ':path': '/', // HTTP/2 uses pseudo-headers prefixed with : ':method': 'GET' }); // Listen for the response headers req.on('response', (headers, flags) => { console.log('statusCode:', headers[':status']); // :status is the HTTP/2 equivalent of statusCode console.log('headers:', headers); }); // Stream the response data to stdout req.on('data', (d) => { process.stdout.write(d); }); // Clean up the session once the request finishes req.on('end', () => { console.log('\nRequest completed successfully'); session.close(); // Close the session to avoid lingering connections }); // Handle request-specific errors req.on('error', (err) => console.error('Request error:', err)); // Finalize the request (this triggers the request to be sent) req.end();
Key Differences from Your Original HTTPS Code:
- Session-based connections: HTTP/2 uses persistent sessions instead of one-off requests. We use
http2.connect()to create a session with the server, then spawn individual request streams from that session. - Pseudo-headers: HTTP/2 replaces standard HTTP/1.1 fields like
pathandmethodwith pseudo-headers prefixed with:(e.g.,:path,:method,:status). These are required for HTTP/2 requests. - Error handling: We handle errors at both the session level (for connection issues) and request level (for individual request failures) to cover more edge cases.
- Resource cleanup: It's good practice to close the session with
session.close()once you're done with requests to avoid resource leaks.
Optional: Custom Connection Options
If you need to pass custom options (like custom CA certificates, disabling certificate validation, etc.), you can add them as the second argument to http2.connect(), just like you did with https.request():
const fs = require('fs'); const session = http2.connect('https://encrypted.google.com', { ca: fs.readFileSync('./custom-root-ca.pem'), rejectUnauthorized: true // Default is true; set to false only for testing });
Give this a shot—this should replicate your original HTTPS request's behavior but over HTTP/2. If you run into any snags with specific use cases (like streaming large payloads or handling server push), feel free to follow up!
内容的提问来源于stack exchange,提问作者Oliver Weichhold

