-1

I use the http module and I need to get the req.body currently I try with the following without success .

http.createServer(function (req, res) {

console.log(req.body);

this return undfiend ,any idea why? I send via postman some short text...

07_05_GuyT
  • 2,787
  • 14
  • 43
  • 88

2 Answers2

2

Here's a very simple without any framework (Not express way).

var http = require('http');
var querystring = require('querystring');

function processPost(request, response, callback) {
    var queryData = "";
    if(typeof callback !== 'function') return null;

    if(request.method == 'POST') {
        request.on('data', function(data) {
            queryData += data;
            if(queryData.length > 1e6) {
                queryData = "";
                response.writeHead(413, {'Content-Type': 'text/plain'}).end();
                request.connection.destroy();
            }
        });

        request.on('end', function() {
            request.post = querystring.parse(queryData);
            callback();
        });

    } else {
        response.writeHead(405, {'Content-Type': 'text/plain'});
        response.end();
    }
}

Usage example:

http.createServer(function(request, response) {
    if(request.method == 'POST') {
        processPost(request, response, function() {
            console.log(request.post);
            // Use request.post here

            response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
            response.end();
        });
    } else {
        response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
        response.end();
    }

}).listen(8000);

express framework

In Postman of the 3 options available for content type select "X-www-form-urlencoded".

app.use(bodyParser.urlencoded())

With:

app.use(bodyParser.urlencoded({
  extended: true
}));

See https://github.com/expressjs/body-parser

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart

karthick
  • 5,998
  • 12
  • 52
  • 90
  • Thanks I use it now but Im getting error Error: read ECONNRESET at exports._errnoException (util.js:746:11) any idea why? – 07_05_GuyT Jun 21 '15 at 19:37
  • I was able to see the data in the console but I got this error afterwards – 07_05_GuyT Jun 21 '15 at 19:41
  • This is network error. Please check the server logs, or handle the uncaught errors process.on('uncaughtException', function (err) { console.error(err.stack); });. Then you may know where exactly error is popping out – karthick Jun 21 '15 at 19:50
  • Thanks when i put it I got Error: read ECONNRESET at exports._errnoException (util.js:746:11) at TCP.onread (net.js:559:26) Error: socket hang up – 07_05_GuyT Jun 21 '15 at 19:56
  • any idea how to overcome this? – 07_05_GuyT Jun 21 '15 at 19:56
  • Thanks but Im not using web socket,I update my post with my all program please have a look and try to help – 07_05_GuyT Jun 21 '15 at 20:13
0

req.body is a Express feature, as far as I know... You can retrieve the request body like this with the HTTP module:

var http = require("http"),
server = http.createServer(function(req, res){
  var dataChunks = [],
      dataRaw,
      data;

  req.on("data", function(chunk){
    dataChunks.push(chunk);
  });

  req.on("end", function(){
    dataRaw = Buffer.concat(dataChunks);
    data = dataRaw.toString();

    // Here you can use `data`
    res.end(data);
  });
});

server.listen(80)
  • Thanks I try it but I got this error :http.createServer(function(req, res) { ^^^^ SyntaxError: Unexpected identifier – 07_05_GuyT Jun 21 '15 at 18:45
  • @shopiaT, I don't get any errors, are you sure you're requiring the http module at the top? I can edit the post really quick to include everything. –  Jun 21 '15 at 18:50
  • Thanks Jamen Its working! one thing when I put large file I got error do you know if I need to add some additional configuration ? – 07_05_GuyT Jun 21 '15 at 18:56
  • @shopiaT, if you're uploading files, handle them with `dataRaw` (the buffer) and not with `data` (the string render) –  Jun 21 '15 at 18:57
  • Not sure that I got it,I send some large file (5000 lines ) and I got error { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' } { [Error: socket hang up] code: 'ECONNRESET' } – 07_05_GuyT Jun 21 '15 at 18:58
  • I send the file in the body, how should I avoid this error? – 07_05_GuyT Jun 21 '15 at 18:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81129/discussion-between-shopia-t-and-jamen). – 07_05_GuyT Jun 21 '15 at 18:59
  • This is a bad example. First of all, local request data (`dataRaw`, `data`) should not be "global" unless you don't care if data from concurrent requests get mixed together. Secondly, calling `Buffer.concat()` on every chunk is unnecessary. Just make a local array and append the chunks to it, then call `Buffer.concat()` inside the `end` handler. Third, `req.end()` does not exist because `req` is a _Readable_ stream, not a _Writable_ stream. Fourth, `req.body` is typically a _parsed_ version of the body, not typically the raw body itself. – mscdex Jun 22 '15 at 04:29
  • @mscdex, There, I made it better. –  Jun 22 '15 at 08:50