V
V
Vladimir Krauz2016-08-14 03:08:00
JavaScript
Vladimir Krauz, 2016-08-14 03:08:00

NodeJS How to get the content of a post request?

Good evening.
We need to get the content of the post request.
I receive the post request itself in chunks, that is, I receive it in raw form.
How to get passed binary data from post request?
(How do I get it and what do I do with it next)

app.post('/', function(req,res,next){ 

  var data = [];
  
  req.on('data', function(chunk) { 
    data.push(chunk);
  });

  req.on('end', function() { 
    var buffer = ...; // Как получить содержимое?
    var file = Buffer.concat(buffer);
    res.end('try');
  });
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Krauz, 2016-08-14
@MelancholicTheDie

I'll answer myself.
It turned out to implement what I needed with the help of: https://github.com/mscdex/busboy
It is updated and works stably.
The simplest example:

var http = require('http'),
    inspect = require('util').inspect;

var Busboy = require('busboy');

http.createServer(function(req, res) {
  if (req.method === 'POST') {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
      file.on('data', function(data) {
        console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      });
      file.on('end', function() {
        console.log('File [' + fieldname + '] Finished');
      });
    });
    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
      console.log('Field [' + fieldname + ']: value: ' + inspect(val));
    });
    busboy.on('finish', function() {
      console.log('Done parsing form!');
      res.writeHead(303, { Connection: 'close', Location: '/' });
      res.end();
    });
    req.pipe(busboy);
  } else if (req.method === 'GET') {
    res.writeHead(200, { Connection: 'close' });
    res.end('<html><head></head><body>\
               <form method="POST" enctype="multipart/form-data">\
                <input type="text" name="textfield"><br />\
                <input type="file" name="filefield"><br />\
                <input type="submit">\
              </form>\
            </body></html>');
  }
}).listen(8000, function() {
  console.log('Listening for requests');
});

M
Mikhail Osher, 2016-08-14
@miraage

https://www.npmjs.com/package/body-parser

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question