简体   繁体   English

在 Node HTTP2 流中发送和接收 JSON

[英]Sending and receiving JSON in Node HTTP2 streams

I'm working on building an authentication microservice in Node using HTTP2.我正在使用 HTTP2 在 Node 中构建身份验证微服务。

How do I properly write JSON to and read it from Node HTTP2 streams?如何正确地将 JSON 写入 Node HTTP2 流并从中读取它?

The documentation gives these examples:文档给出了这些示例:

const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
});
server.on('error', (err) => console.error(err));

server.on('stream', (stream, headers) => {
  // stream is a Duplex
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.end('<h1>Hello World</h1>');
});

server.listen(8443);

and

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));

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();

Let's say I have a JSON object which I want to write to the stream in the client and read from the stream in the server, and vice versa.假设我有一个JSON对象,我想将它写入客户端中的流并从服务器中的流中读取,反之亦然。 How do I do this properly?我该如何正确执行此操作?

I can stringify my JSON to str and use request.write(str, 'utf-8) , but is that the optimal way?我可以将我的JSON字符串化为str并使用request.write(str, 'utf-8) ,但这是最佳方式吗? And how do I listen for the JSON on the other side in order to handle it?我如何在另一端监听 JSON 以处理它?

The server...服务器...


const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
});

server.on('error', (err) => {
  console.error(err)
});

server.on('stream', (stream, headers) => {
  // stream is a Duplex
  
  // headers[:path] is the normal request from browser. A path url.

  console.log("Request from client: " + headers[:path]);
  

  req.on("data", (data) => {
    console.log("Data from HTTPS2 client(event): " + data);
    // It is just the data from 'POST' method.
  });



stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });

  stream.end('<h1>Hello World</h1> Or a string, other data, wherever you want...');

});

server.listen(8443);

The Client.客户端。 Can be a XHR request in 'GET' or 'POST' method.可以是“GET”或“POST”方法中的 XHR 请求。 Server side is the same.服务器端是一样的。 To 'GET' mode use method = GET and remove "req.end('XXX any string. bla, bla, bla');"要使用“GET”模式,请使用 method = GET 并删除“req.end('XXX any string.bla, bla, bla');”

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)
});

//':method': 'GET/POST' Can be just one.
const req = client.request({ ':method': 'POST', ':path': '/' });

req.on('response', (headers, flags) => {
  for (const name in headers) {
    console.log(`${name}: ${headers[name]}`);
  }
});

req.setEncoding('utf8');
let data = '';

//Data from HTTPS2 server.
req.on('data', (chunk) => { 

  data += chunk; 

});

req.on('end', () => {
  console.log(`\n${data}`);
  client.close();
});

//Only for POST method.
req.end("The data you want to send. String, JSON, buffer whatever...");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM