Sunday, 19 March 2017

express.js 4 has broken request.on('data') triggering

I'm hoping someone can either find what I'm doing wrong or can verify what I'm discovering to be true.

On a post to a node.js server there just isn't any way in the world request.on('data') works. Body-parser/json just isn't setting up express correctly or express isn't doing it's job, or both.

Following are two paired projects, one server & one client to send a post to the server. Both are in node.js. The server includes express & body-parser

This is server side:

/* Used to start Node
var debug = require('debug')('ExpressApp1');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});
*/

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var fRawBody = function (req, res, buf, encoding) {
    if (buf && buf.length) {
        req.rawBody = buf.toString(encoding || 'utf8');
        console.log("buf", req.rawBody);
    }
}

app.use('/', bodyParser.json({ verify: fRawBody }));

app.use('/', function (req, res, next) {
    var data = '';
    req.on('data', function (chunk) {
        console.log('data');
        data += chunk;
    });
    req.on('end', function () {
        req.rawBody = data;
        console.log("raw", req.rawBody);
    });
    res.sendStatus(200);
});


module.exports = app;

--- end of app.js ----

This is the client.

Client side response.on('data') works fine.

var http = require("http");

var options = {
    "method": "POST",
    "hostname": "127.0.0.1",
    "port": "1337",
    "path": "/",
    "headers": {
        "content-type": "application/json",
        "cache-control": "no-cache",
        "postman-token": "44e8850a-7a9d-42ce-fbbf-02ac3e6e051b"
    }
};

var req = http.request(options, function (res) {
    var chunks = [];

    res.on("data", function (chunk) {
        chunks.push(chunk);
    });

    res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
    });
});

req.write(JSON.stringify({ data: { theGreatest: 'SMT' } }));
req.end();

I'm hoping someone can either find what I'm doing wrong or can verify what I'm finding out to be true.

Node.js 4.2.4 (client & server)

Express 4.9.8 (server)

Body-Parser.js 1.8.4 (server)

Thanks.



via user2367083

No comments:

Post a Comment