viswanath
viswanath

Reputation: 13

res.locals,req.variable returned undefined in node.js

I'm new to node.js,and I'm writing an API,but have one basic problem. I'm trying to access value in app.js which is set to res.locals or(req object) in validateSession.js,giving undefined.

Would this be a proper use of middleware?

How can i use middleware result in app.js?

app.js

app.post('/api/JSONSrv',validateSession,function(req,res){
console.log(req.dbResult)
})

validateSession.js

    function validateSession(req,res,next){
        if(someCondition){
           oracledb.getConnection(
                {
                  user          : dbConfig.user,
                  password      : dbConfig.password,
                  connectString : dbConfig.connectString
                },
                function (err, connection) {
                  if (err) { console.error(err.message); return; }
                  var plsql=`BEGIN CREATE_OR_VALIDATE_SESSID(:IN_CORP_ID, :PI_IN_USER_ID, :PI_IN_PASSWORD, :PI_IN_JSONLENGTH,:PI_IN_URL, :PO_IN_DOCKET, :STATUS, :OUT_ERROR_DESC, :OUT_DOCKET);
                  END;`;

            var bindvars = {

             };

               connection.execute(plsql,bindvars,function (err, result) {
                      if (err) {
                        doRelease(connection);
                         return;
                     }
                  console.log(result.outBinds);
                  req.dbResult=result.outBinds;//giving undefined in app.js
                 res.local.dbResult=result.outBinds;//giving undefined in app.js
                  doRelease(connection);
                  });
            });
            }else{
            res.json({
                Error_Desc:'Invalid payload length'
            })
        }
         next();
    }
module.exports.validateSession=validateSession;

Upvotes: 1

Views: 1096

Answers (1)

robertklep
robertklep

Reputation: 203514

You're not waiting for the query results before you call next().

Restructure your code to something similar to this:

if (someCondition) {
  ...
  connection.execute(plsql,bindvars,function (err, result) {
    ...
    doRelease(connection);
    next();
  });
} else {
  next();
}

Upvotes: 1

Related Questions