I'm trying to figure out how to send an HTTP/2 POST request with NodeJS. I have so far from the example in the documentation:
const http2 = require('http2');
const fs = require('fs');
const client = http2.connect('https://localhost:8443', {
ca: fs.readFileSync('localhost-cert.pem')
});
client.on('error', (err) => console.error(err));
client.on('socketError', (err) => console.error(err));
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
for (const name in headers) {
console.log(`${name}: ${headers[name]}`);
}
});
req.setEncoding('utf8');
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
console.log(`\n${data}`);
client.close();
});
req.end();
But there it isn't clear to me how to actually setup data to send as a POST.
After piecing together little bits of information everywhere, I've finally manage to resolve this issue. Here is a template example. The key is in req.write(). I honestly couldn't find anywhere a direct answer for how to include a body. Nearly every example is without a body! Hope this helps others. NOTE: This is in Node-red hence the global.get statements, but also works by changing those to require('module'):
If you need to post your objects as json - you should stringify it and wrap in buffer. Here is the code that works in my case:
Try to compose your request body as below:
There're different ways to post data, in body, or form etc. Download postman, configure your post request in it and it has a feature to generate code samples for different languages. Node.JS is one of them.
I also recommend you use
request
package. It encapsulates some functions and makes it easier to receive data. request