Reputation: 1276
I am very new to Node Js and Concept of Callback Mechanism , I have working code to authenticate the User based on the LDAP using ldapjs
but I wanted to know the mechanism how its working with respect to data flow and callbacks.
In the below code I have few doubts, Can someone help me clarifying
cb(err === null, err, res);
true
Why its true?Before asking this question I have gone through many forums but couldn't relate with the below code
var express = require('express');
var util = require('util');
CircularJSON = require('circular-json');
var router = express.Router();
var ldap = require('ldapjs');
var bodyParser = require('body-parser');
var userNT;
var password;
var app = express();
function authDN(dn, password, cb, res) {
var client = ldap.createClient({
url: 'ldap://localhost:389'
});
client.bind(dn, password, function(err) {
client.unbind();
cb(err === null, err, res);
});
}
function output(fake_res, err, res) {
if (fake_res) {
console.log('success');
res.status(200).send('{"status":"success"}');
} else {
console.log('failure');
res.status(401).send('{"status":"failure"}');
}
}
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
extended: true
})); // support encoded bodies
router.post('/login', postData);
function postData(req, res) {
userNT = req.body.ntid;
password = req.body.password;
authDN(userNT, password, output, res);
};
module.exports = router;
Upvotes: 0
Views: 1072
Reputation: 835
Okay let us go try to do it step by step :
Here if you see authDN
has third parameter cb
this is your callback function. Now to trace it back check the value of argument provided to this function authDN
when it is called inside postData
function, here cb = function output
Now first param of your output is fake_res which is either true or false, this depends on response of client.bind
If it fails you will get some error hence it will go on to be false. Here comes the answer to your question 2 because your credentials seem to be correct always this err is equal to null thus your fake_res is always true.
Answering question 4 it is because it is passed on as param to send response back to the API call you made using router.post
About number 3 it is just more readable and better to use an error first callback, but not necessary.
Upvotes: 1