使用回调函数结果在NodeJS中实现res.render

时间:2017-03-13 19:59:28

标签: javascript node.js express oracledb-npm

我正在使用oracledb来从节点获取数据库中的数据。获取数据后,我尝试使用快速JS中的 render()将数据发送到客户端。代码是这样的 -

config.js

module.exports = {
  user          : "user",
  password      : "password",
  connectString : "*connstring*"  ,
  deliveredQuery: " SELECT COUNT (DISTINCT order_num) AS Cnt from orders where department = 'HR'
};

query2.js

module.exports = function(callback) {//pass callback function and return with this
  var oracledb = require('oracledb');
  var dbConfig = require('./config.js');

  this.queryDB = function(query,callback) {
    oracledb.getConnection({
      user: dbConfig.user,
      password: dbConfig.password,
      connectString: dbConfig.connectString,
      deliveredQuery: dbConfig.deliveredQuery    
    }, function(err, connection) {
      if (err) {
        console.error(err.message);
        return callback(err);
      }
      connection.execute(query, function(err, result) {
        if (err) {
          console.error(err.message);
          doRelease(connection);
          return;
        }
        //console.log(result.metaData);
        //console.log(JSON.parse(result.rows[0][0]));
        doRelease(connection);
        return callback(null, JSON.parse(result.rows[0][0]))
      });
    });

    function doRelease(connection) {
      connection.release(function(err) {
        if (err) {
          console.error(err.message);
          return callback(err);
        }
      });
    }
  };
};

serv_ontime.js

var dbConfig = require('./config.js');
var res = require('./query2.js')();
var onTime_query = dbConfig.onTime_query;

module.exports = function (callback) {
    queryDB(onTime_query, callback)
};

app.js

var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORT || 5000;

var serv_ontime = require('./serv_ontime.js');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/src/views');   
var bookRouter= express.Router();
app.set('view engine','ejs');

    bookRouter.route('/')
          .get(function(req,res){
              serv_ontime(function(error, result){
                  res.render('index', 
                                    {title: 'Hello',
                                     rec: result
                                    });
              });
          });

现在,当我在cmd中执行节点app.js 时,它显示以下错误 -

Error

有谁能帮我理解我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

dbconfig.js中的onTime_query在哪里:

var onTime_query = dbConfig.onTime_query;

你确定它是写的。