Node.js HTTP 服务器请求体作为流可读对象

3

我正在使用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');

根据Node的文档,请求参数是http.IncomingObject的实例,该实例实现了Node的可读流接口。上述代码中仅使用stream.pipe()存在问题,即可读流包括请求头的纯文本以及请求体。是否有办法仅将请求体作为可读流进行隔离?
我知道有一些针对文件上传的框架,例如formidable。我的最终目标不是创建一个上传服务器,而是充当代理并将请求体流式传输到另一个Web服务。
提前致谢。
编辑>>使用busboy处理"Content-type: multipart/form-data"的工作服务器
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');

你确定这些是头文件吗?这不应该发生。 - vkurchatkin
1个回答

1
检查你的req.headers['content-type']。如果它是multipart/form-data,那么你可以使用像busboy这样的模块来解析请求,并为文件部分提供可读流(如果存在非文件部分,则为普通字符串)。
如果内容类型是其他一些multipart/*类型,则可以使用dicer,这是busboy用于解析多部分的底层模块。

感谢 @mscdex,您提到的请求头非常准确。我进行了一些尝试,如果我使用 Content-type: application/x-www-form-urlencoded 发送请求,我的原始代码可以正常工作。如果我使用 Content-type: multipart/form-data 发送请求,则 busboy 解决方案效果很好。请参见上面的编辑以获取该解决方案。 - heinrichduesseldorf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接