отправка http/2 POST-запроса в Node.js
Как отправить http/2 post-запрос в Node.js? Хочу отправить следующий запрос.
curl --http2 "POST" "http://hostname:8088/query-stream" -d $'{"sql": "SELECT * FROM `USERPROFILE` EMIT CHANGES;", "properties": {"ksql.streams.auto.offset.reset": "earliest" } }'
2 ответа
У вас должна быть возможность использовать node-fetch и что-то вроде этого:
const body = {"sql": "SELECT * FROM `USERPROFILE` EMIT CHANGES;", "properties": {"ksql.streams.auto.offset.reset": "earliest" } };
fetch('http://hostname:8088/query-stream', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
Я решил проблему. Если кому-то нужна трость, чтобы использовать следующий код
const http2 = require('http2');
const http2PostRequest = (url, path, data) => new Promise((resolve, reject) => {
console.log('url => ', url);
console.log('data => ', data);
const client = http2.connect(url);
console.log(' http2.constants.HTTP2_METHOD_POST => ', http2.constants.HTTP2_METHOD_POST)
console.log(' http2.constants.HTTP2_PATH => ', `${path}`);
const req = client.request({
[http2.constants.HTTP2_HEADER_SCHEME]: "https",
'Content-Type': 'application/json',
'Content-Length': data.length,
":method": "POST",
":path": path
});
req.setEncoding('utf8');
req.on('response', (headers, flags) => {
console.log('headers => ', headers);
console.log('flags => ', flags);
req.on('data', d => {
console.log('data => ', JSON.parse(d));
})
req.on('close', () => {
try {
resolve(data);
} catch (e) {
resolve(e);
}
})
req.on('error', error => {
reject(error);
})
});
req.write(data);
req.end();
});
const data = {
"sql": "SELECT * FROM `FOO_02` EMIT CHANGES;",
"properties": {"ksql.streams.auto.offset.reset": "earliest"}
};
http2PostRequest(
"http://localhost:8088",
"/query-stream",
JSON.stringify(data)
).then((res) => {
console.log('res => ', res);
})