4 min read
•Question 62 of 62hardHow to use HTTP/2 in Node.js?
HTTP/2 server and client implementation.
What You'll Learn
- HTTP/2 features
- Creating HTTP/2 servers
- HTTP/2 clients
HTTP/2 Server
code.jsJavaScript
const http2 = require('http2');
const fs = require('fs');
const server = http2.createSecureServer({
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
});
server.on('stream', (stream, headers) => {
stream.respond({
':status': 200,
'content-type': 'text/html'
});
stream.end('<h1>Hello HTTP/2!</h1>');
});
server.listen(8443);Server Push
code.jsJavaScript
server.on('stream', (stream, headers) => {
const path = headers[':path'];
if (path === '/') {
// Push CSS before it's requested
stream.pushStream({ ':path': '/style.css' }, (err, pushStream) => {
pushStream.respond({ ':status': 200, 'content-type': 'text/css' });
pushStream.end('body { color: blue; }');
});
stream.respond({ ':status': 200, 'content-type': 'text/html' });
stream.end(`
<html>
<link rel="stylesheet" href="/style.css">
<body>Hello!</body>
</html>
`);
}
});HTTP/2 Client
code.jsJavaScript
const http2 = require('http2');
const client = http2.connect('https://localhost:8443', {
rejectUnauthorized: false
});
const req = client.request({ ':path': '/' });
req.on('response', (headers) => {
console.log('Status:', headers[':status']);
});
let data = '';
req.on('data', chunk => data += chunk);
req.on('end', () => {
console.log(data);
client.close();
});