node.jsexpressmean-stackmean.ioldapjs

How to Run the Function with Express POST based the response from the Previous Middleware


I am very new to MEAN.io

Below Function(authDN) written & which is working fine on running alone like below.

when I run the function directly I am getting proper response in the console

authDN('myuserName', 'myPassword', output);

But I wanted to run the function with router.post and run the function (authDN) , So whenever POST call is made I wanted to show the response based on the response returned by authDN ,And I wanted to pass the userNT , password from the postData function to the authDN as well

Can someone help me to approach this

var express = require('express');
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) {
    var client = ldap.createClient({ url: 'ldap://localhost:389' });
    client.bind(dn, password, function (err) {
        client.unbind();
        cb(err === null, err);
    });

}

function output(res, err) {
    if (res) {
        console.log('success');
    } else {
        console.log('failure');
    }
}



app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false })); // support encoded bodies

router.post('/login', postData, authDN(userNT, password, output));

function postData(req, res) {
    userNT = req.body.ntid;
    password = req.body.password
};


module.exports = router;

Solution

  • router.post('/login', postData);
    
    function postData(req, res) {
        userNT = req.body.ntid;
        password = req.body.password;
        authDN(userNT, password, output,res);   //send res also
    };
    
    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); //pass res to callback
        });
    
    }
    
    function output(fake_res, err, res) {
        if (fake_res) {
           console.log('success');
           res.send('success')   //here
        } else {
           console.log('failure');
           res.send('failure')   //here
        }
    }