我是 node.js 的新手,我正在编写一个 API,但有一个基本问题。 我正在尝试访问 app.js 中的值,该值设置为 res.locals 或 validateSession.js 中的(req 对象),未定义。
这是对中间件的正确使用吗?
如何在 app.js 中使用中间件结果?
应用程序.js
app.post('/api/JSONSrv',validateSession,function(req,res){
console.log(req.dbResult)
})
验证 session .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;
最佳答案
在调用 next()
之前,您无需等待查询结果。
将您的代码重组为类似于此的内容:
if (someCondition) {
...
connection.execute(plsql,bindvars,function (err, result) {
...
doRelease(connection);
next();
});
} else {
next();
}
关于javascript - res.locals,req.variable 在 node.js 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53318913/