热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

发送HTTP/2POST请求NodeJS

如何解决《发送HTTP/2POST请求NodeJS》经验,为你挑选了1个好方法。

我试图弄清楚如何使用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());
    });
});


推荐阅读
author-avatar
大女人小诺
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有