0

I've got a node.js-based webserver running at home and i'm trying to implement a login form.

So basically I need to access POSTed data (login/password). I found this : How do you extract POST data in Node.js? (req.on('data'...) & req.on('end'...))

But i need to do this asynchronously, can someone tell me how to do that ? (I need this code to be blocking, not non-blocking)

EDIT: All my code is available on Github : https://github.com/Fointard/NodeJs/tree/authentication The problem lies here : https://github.com/Fointard/NodeJs/blob/authentication/js/reqHandlers/auth.js Lines 98 and 104, i'm relying on 'data' and 'end' envents but i'd like to do that asychronously so that checkID() (line 95) is able to return true or false.

Community
  • 1
  • 1
Fointard
  • 43
  • 1
  • 7
  • Can you provide some code? What have you done until now? Are you using node's http server, express or something else? – goenning Apr 11 '16 at 15:56
  • You're saying that you need it to be `blocking` but also `asychronously`. That does not make sense. – goenning Apr 12 '16 at 10:54
  • Wait. Synchronous is blocking & asynchronous is non-blocking ? If so, my bad, I meant synchronously. – Fointard Apr 12 '16 at 12:50
  • Yes, synchronous is blocking. Since node.js is single threaded, synchronous/blocking [should be avoided](http://www.nodewiz.biz/your-doing-node-js-wrong-avoid-synchronous-code/) at all cost. – goenning Apr 12 '16 at 13:24

1 Answers1

0

You can't. HTTP Requests are I/O operations and will always be resolved asychronously. Your checkID function will never return a value. You need to add a second parameter (usually called callback) that will be called with true or false.

function checkID(req, callback) {
  var body = '';
  req.on('data', function (data) {
    body += data;
    if (body.length > 1e6)
        req.connection.destroy();
  });

  req.on('end', function () {

    var post = qs.parse(body);

    if ('loginInputLogin' in post && 'loginInputPassword' in post) {
        console.log('login : '+post['loginInputLogin']);
        console.log('password : '+post['loginInputPassword']);
    }

    if (post['loginInputLogin'] === 'fointard' && post['loginInputPassword'] === 'f01n') {
        console.log('ID confirmed');

        callback(true);
    }

    callback(false);
  });
}

And use it like so:

checkID(yourRequest, function(success) {
  if(success) {
    //login successfull
  } else {
    //login failed
  }
})
goenning
  • 6,514
  • 1
  • 35
  • 42