抛出新的TypeError('Router.use()需要中间件函数,但得到'+ gettype(fn));

时间:2017-09-25 04:26:30

标签: javascript node.js express mongojs

我已经使用MongoJS创建了一个快速应用程序。我正在返回一个函数,它仍然显示一个对象已被返回。我甚至在我的JavaScript页面中添加了module.exports=router。有人可以在这里指出丢失的出口吗?

app.js

var express = require('express');
var define = require('./user/userSlots');
var app = express();
app.set("views", "./view");
app.use('/', define);
app.listen(3111, function () {
    console.log('Example app listening on port 3111!');
});

userSlots.js

var express = require('express');
var module = require('../admin/dbModule');
var router = express.Router();

router.get('/login', function(request, response) {
    var username = request.params.username;
    var email = request.params.email;
    module.authenticateUser(username, email, response);
});
module.exports = router;

dbModule.js

var mongojs = require("../../node_modules/mongojs");
var databaseUrl = "localhost/user";
var db = mongojs(databaseUrl);
var test = db.collection('user_information');
var message = null;
db.user_information.ensureIndex({ email: 1 }, { unique: true });
exports.authenticateUser = function(username, email, response) {
    db.user_information.find({ username: username, email: email }, function(err, users) {
        if (err || !users) {
            console.log("Failure");
            message = "Failure";
            reponse.render('index', { title: 'Hello', message: message });
        } else if (users.length == 0) {
            console.log("Not Valid user");
            message = "Failure";
            reponse.render('index', { title: 'Hello', message: message });
        } else {
            console.log("valid");
            message = "Success";
            reponse.render('index', { title: 'Hello', message: message });
        }
    });
}

错误:

E:\Vehicles\vehicles.com\node_modules\express\lib\router\index.js:458

      throw new TypeError('Router.use() requires middleware function but got a '
 + gettype(fn));
      ^

TypeError: Router.use() requires middleware function but got a Object
    at Function.use (E:\Vehicles\vehicles.com\node_modules\express\li
b\router\index.js:458:13)
    at EventEmitter.<anonymous> (E:\Vehicles\vehicles.com\node_module
s\express\lib\application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (E:\Vehicles\vehicles.com\node_modules\expres
s\lib\application.js:217:7)
    at Object.<anonymous> (E:\Vehicles\vehicles.com\application\app.j
s:12:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

1 个答案:

答案 0 :(得分:1)

通过在此行中重新定义module来解决问题:

var module = require('../admin/dbModule');

然后,期待它成为原始的内置module以后:

module.exports = router;

改变这个:

var module = require('../admin/dbModule');

使用其他名称:

var dbModule = require('../admin/dbModule');

然后,使用dbModule引用您的数据库模块,然后内置的module仍可在module.exports中正常使用。