【问题标题】:node js http server request body as stream readable节点 js http 服务器请求正文作为流可读
【发布时间】:2014-06-27 17:51:37
【问题描述】:

我正在使用 node.js 编写一个 http 服务器,并且无法将请求正文隔离为可读流。这是我的代码的基本示例:

var http = require('http')
  , fs = require('fs');

http.createServer(function(req, res) {
  if ( req.method.toLowerCase() == 'post') {
    req.pipe(fs.createWriteStream('out.txt'));
    req.on('end', function() {
      res.writeHead(200, {'content-type': 'text/plain'})
      res.write('Upload Complete!\n');
      res.end();
    });
  }
}).listen(8182);
console.log('listening on port 8182');

根据节点的documentation,请求参数是http.IncomingObject的一个实例,它实现了节点的可读流接口。像我上面那样使用 stream.pipe() 的问题是可读流包括请求标头的纯文本以及请求正文。有没有办法仅将请求正文隔离为可读流?

我知道有一些用于文件上传的框架,例如 formidable。我的最终目标不是创建上传服务器,而是充当代理并将请求正文流式传输到另一个 Web 服务。

提前致谢。

编辑>> 使用 busboy 的“内容类型:多部分/表单数据”的工作服务器

var http = require('http')
  , fs = require('fs')
  , Busboy = require('busboy');

http.createServer(function(req, res) {
  if ( req.method.toLowerCase() == 'post') {
    var busboy = new Busboy({headers: req.headers});
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      file.pipe(fs.createWriteStream('out.txt'));
    });
    req.pipe(busboy);
    req.on('end', function() {
      res.writeHead(200, 'Content-type: text/plain');
      res.write('Upload Complete!\n');
      res.end();
    });
  }
}).listen(8182);
console.log('listening on port 8182');

【问题讨论】:

  • 你确定这些是标题吗?这不应该发生

标签: node.js http stream request


【解决方案1】:

检查您的req.headers['content-type']。如果是multipart/form-data,那么您可以使用busboy 之类的模块为您解析请求,并为您提供文件部分的可读流(如果存在非文件部分,则为纯字符串)。

如果 content-type 是其他 multipart/* 类型,那么您可以使用 dicer,这是 busboy 用于解析 multipart 的底层模块。

【讨论】:

  • 感谢@mscdex,您对请求标头的概念是正确的。我玩了一下,如果我用Content-type: application/x-www-form-urlencoded 发送我的请求,我的原始代码就可以工作。如果我使用Content-type: multipart/form-data 发送请求,那么busboy 解决方案效果很好。有关该解决方案,请参见我上面的编辑。
猜你喜欢
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2021-01-31
  • 2022-11-09
  • 2021-03-24
  • 2018-02-15
  • 2018-02-03
  • 2023-04-11
相关资源
最近更新 更多