No One
No One

Reputation: 67

Unsuccessful POST request handling

<form method="POST" action="/profile">
    <input name="name" type="text"><br/>
    <input name="password" type="password"><br/>
    <input type="submit">
</form>

I am trying to send a POST request to a node.js file using this form And to process the request I did the following after creating the server :

if (request.method === 'POST') {
    var data = '', dataFull;
    request.on('data', function (chunk) {
        data += chunk;
    }).on('end', function () {
        dataFull = queryString.parse(data);
    });
    console.log(dataFull);
}

But the console just logs undefined instead of logging the object. And tried logging the data variable but it logged nothing

Can anyone explain why?

Upvotes: 1

Views: 79

Answers (1)

riyaz-ali
riyaz-ali

Reputation: 9102

That's because the dataFull variable is not populated by the time you reach the console.log(dataFull) statement. The callbacks you bind on the data and end are asynchronous and are only fired when the respected events occur. Checkout this link to learn more about async callbacks (and lot more).
As far as the code is concerned, you can do something like this,

if (request.method === 'POST') {
  let data = '';
  request.on('data', function (chunk) {
    data += chunk;

    // Too much POST data, kill the connection!
    // someone can kill node by uploading an endless file! 
    // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
    if(data.length > 1e6){
      request.connection.destroy();
    }
  }).on('end', function () {
    let dataFull = queryString.parse(data);
    console.log(dataFull);
    //- now you can access the fields as dataFull['name'] etc.
    //- maybe call a callback or resolve a promise here
    //- cb(null, dataFull) or resolve(dataFull)
  });
}

P.S. Body nuking example taken from this SO answer and it's comments

Upvotes: 1

Related Questions