【问题标题】:Sending and receiving JSON in Node HTTP2 streams在 Node HTTP2 流中发送和接收 JSON
【发布时间】:2019-03-21 03:51:34
【问题描述】:

我正在使用 HTTP2 在 Node 中构建身份验证微服务。

如何正确地将 JSON 写入 Node HTTP2 流并从中读取?

documentation 给出了这些例子:

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

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

假设我有一个JSON 对象,我想将其写入客户端中的流并从服务器中的流中读取,反之亦然。我该如何正确地做到这一点?

我可以将我的JSON 字符串化为str 并使用request.write(str, 'utf-8),但这是最佳方式吗?以及如何侦听另一端的 JSON 以进行处理?

【问题讨论】:

    标签: node.js stream http2 node-streams


    【解决方案1】:

    服务器...

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

    客户。可以是“GET”或“POST”方法中的 XHR 请求。服务器端也是一样。 在 '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...");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      相关资源
      最近更新 更多