Skip to content

Instantly share code, notes, and snippets.

@zhrebicek
Last active July 15, 2022 11:08
Show Gist options
  • Save zhrebicek/96cc0a357948b70a81441f7edad82cec to your computer and use it in GitHub Desktop.
Save zhrebicek/96cc0a357948b70a81441f7edad82cec to your computer and use it in GitHub Desktop.
http2 with NodeJs
const http2 = require('http2');
try {
const api_host = "https://localhost:8080";
const client = http2.connect(api_host);
const path = "/my_endpoint";
const api_key = "ffff-eee-ddd";
const write_request = [1, 2, 3, 4, 5];
const req = client.request({
[http2.constants.HTTP2_HEADER_SCHEME]: "https",
[http2.constants.HTTP2_HEADER_METHOD]: http2.constants.HTTP2_METHOD_POST,
[http2.constants.HTTP2_HEADER_PATH]: path,
[http2.constants.HTTP2_HEADER_AUTHORITY]: api_host.replace('https://', ''),
[http2.constants.HTTP2_HEADER_CONTENT_LENGTH]: write_request.length,
[http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + api_key,
});
let data = [];
req.on('data', (chunk) => data += chunk);
req.on('response', (headers, flags) => {
logger.log(`HEADERS: ${JSON.stringify(headers)}`);
});
req.write(write_request, 'utf8');
req.end();
} catch (error) {
if (error) {
logger.log('Skipping, cannot send data: ' + error.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment