user2367083 user2367083 -4 years ago 139
Javascript Question

node.js ~ express req.on('end') triggers but not req.on('data')

Using body parser either



  • application/x-www-form-urlencoded body parser




or



  • json body parser




Yields the same results.

This is how I'm calling the API

$.ajax({ type:'post', url:'/api/order', headers: { 'GreatestHits': 'SteveMillerBand' }, data: { 'the': 'greatest' } });


Why isn't
.on('data')
triggering
? Isn't
body
simply the
data
object of the request, pretty much
? I am seeing the form data logging to the console. I can also direct the post to
http://httpbin.org/post
to prove the point.
I can only believe the Express is the real c@ blocker. If that is not it then I at a loss.

// this is the code being called by the $.ajax()
app.use(function (req, res) {
console.log("app.use req.data", req.data);
req.on('data', function (chunk) {
console.log("req.use on data");
}).on('end', function () {
console.log("app.use on end");
});
res.sendStatus(200);
});


On the
$.ajax()
post each of the following models, based on the above code, results as shown:

app.use(callback() {} )




  • has req.body

  • does not have req.data (undefined)


    • will NOT trigger .on('data');

    • will NOT trigger .on('end');





.

app.post(callback() {} )




  • will not even be called unless a route string is included.




.
app.post('route', callback() {} )




  • has
    req.body

  • does not have
    req.data
    (undefined)


    • will NOT trigger
      .on('data');

    • will NOT trigger
      .on('end');





.

app.use('route', callback() {} )




  • has
    req.body

  • does not have
    req.data
    (undefined)


    • will NOT trigger
      .on('data');

    • will trigger
      .on('end');




Answer Source

The comment thread is too long already to continue adding to it. Not knowing what better I can do I'm posting this as an answer to continue the conversation.

This code triggers .on('end')

app.use(function (req, res, next) {
    console.log("app.use req.data", req.body);
    req.on('data', function (chunk) {
        console.log("req.use on data");
    }).on('end', function () {
        console.log("app.use on end");
    });
    next();
});

This is the call to the above;

$.ajax({ type:'post', url:'/api/order', headers: { 'GreatestHits': 'SteveMillerBand' }, data: { 'the': 'greatest' } });

Why isn't .on('data') triggering? I am seeing the form data logging to the console.

Also. If the data segment is know as req.body then why isn't it req.on('body')?

Because, I find out, that Body-Parser.js complete consumes the response object it receives from Node.js & it re-writes it thereby re-creating response as an object expectionally different from the node.js response object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download