作者:大女人小诺 | 来源:互联网 | 2022-12-30 16:46
我试图弄清楚如何使用NodeJS发送HTTP / 2 POST请求。到目前为止,我离文档中的示例还很远:
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();
但是我还不清楚如何实际设置数据以POST方式发送。
1> 小智..:
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:
const http2 = require('http2');
const post = (url, path, body) => new Promise((resolve) => {
const client = http2.connect(url);
const buffer = new Buffer(JSON.stringify(body));
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}`,
"Content-Type": "application/json",
"Content-Length": buffer.length,
});
req.setEncoding('utf8');
let data = [];
req.on('data', (chunk) => {
data.push(chunk);
});
req.write(buffer);
req.end();
req.on('end', () => {
resolve(data: data.join());
});
});