2017-03-19 45 views
0

这是我的app.js:为什么不会这个模块打印

var express = require('express'); 
var app = express(); 
var router = express.Router(); 

var someroute = require('./someroute')(router); 


app.use('/api/someroute', someroute); 


app.listen(3000, function() { 
    console.log('Server listening on port 3000!') 
}); 

这是我someroute.js:

module.exports = function(router) { 
    var security = require('../../lib/security'); 

    router.post("/", function(req, res, next) { 

     console.log('THIS IS PRINTING'); 

     security.security_function(function(err,result){ 
     console.log('THIS IS NOT PRINTING'); 
      }); 
    }); 
    //error handler 
    router.use(function(err, req, res, next) { 
     res.status(500).json(JSON.stringify({ 
      error: err 
     })); 
    }); 
    return router; 
} 

这是我security.js文件:

exports.security_function= function() { 
    console.log("THIS IS NOT PRINTING EITHER"); 
}); 

当我调用/ api/sameroute url时,它碰到路由,因为我可以看到第一个打印的console.log,但是当我期望security_function打印某些东西时什么都不打印。然后结果这个函数带回我也希望它打印,但它显然不是打印,因为security_function似乎没有运行。

+0

'security.js'中的函数后面的右括号是什么? – Bergi

+0

你有什么错误吗? – Bergi

回答

1

您的代码混淆。您已将security_function定义为不带参数的函数。应该简称为security.security_function()这样的:

module.exports = function(router) { 
    var security = require('../../lib/security'); 

    router.post("/", function(req, res, next) { 

     console.log('THIS IS PRINTING'); 

     // call the security function here 
     security.security_function(); 
    }); 
    //error handler 
    router.use(function(err, req, res, next) { 
     res.status(500).json(JSON.stringify({ 
      error: err 
     })); 
    }); 
    return router; 
} 

然后,此外,您不使用路由器正常。你正在做的:

app.use('/api/someroute', someroute); 

someroute在这种类型的代码要么是路由器或它应该是一个中间件功能。这不是你的情况。您将它作为router.post()的函数。这是非常错误的。每次调用中间件时,这将会注册一个新的router.post()处理程序,这绝不是您想要执行的操作。你不解释你想要用这个代码做什么,所以我不能推荐正确的代码,但是这个代码显然是错误的。

0

你错过了回调。请用下面的文件替换security.js文件。

exports.security_function= function(cb) { console.log("THIS IS NOT PRINTING EITHER"); cb(); };