TypeError:Router.use()需要中间件功能,但有一个Object

新版本的express中间件有所更改,我对此问题的其他一些帖子的代码也做了一些更改,但我束手无策。

我们已经事先进行了工作,但是我不记得发生了什么变化。

throw new TypeError('Router.use() requires middleware function but got a
        ^
TypeError: Router.use() requires middleware function but got a Object

node ./bin/www

js-bson: Failed to load c++ bson extension, using pure JS version
js-bson: Failed to load c++ bson extension, using pure JS version

/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438
      throw new TypeError('Router.use() requires middleware function but got a
            ^
TypeError: Router.use() requires middleware function but got a Object
    at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438:13
    at Array.forEach (native)
    at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:436:13)
    at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:188:21
    at Array.forEach (native)
    at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:185:7)
    at Object.<anonymous> (/Users/datis/Documents/bb-dashboard/app.js:46:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var routes = require('./routes/index');
var users = require('./routes/users');

var Users = require('./models/user');
var Items = require('./models/item');
var Store = require('./models/store');
var StoreItem = require('./models/storeitem');

var app = express();
//set mongo db connection
var db = mongoose.connection; 

MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});
// var MONGOHQ_URL="mongodb://localhost:27017/test" 

// view engine setup
app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: 'something',
    resave: true,
    saveUninitialized: true
}));

app.use('/', routes);
app.use('/users', users);
app.use(express.static(path.join(__dirname, 'public')));

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//     var err = new Error('Not Found');
//     err.status = 404;
//     next(err);
// });

// Make our db accessible to our router
app.use(function(req, res, next){
  req.db = db;
  next();
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

似乎由于版本控制原因,此问题的答案已更改。感谢Nik

猿Mandy2020/03/24 17:59:16

在您的任何js页面中,您都缺少

module.exports = router;

检查并验证您的所有JS页面

JinJin乐2020/03/24 17:59:16

如果您正在使用快递并正在做的简单解决方案

const router = express.Router();

确保

module.exports = router ;

在页面末尾

阿飞Tom2020/03/24 17:59:16

我收到了由Anirudh发布的错误和解决方案帮助。我构建了用于快速路由的模板,却忘记了这一细微差别-很高兴这是一个简单的解决方案。

我想通过解释我的文件结构来澄清他的回答,以将代码放在哪里。

我的典型文件结构如下:

/lib

/routes

---index.js (控制主导航)

/page-one



/page-two



     ---index.js

(每个文件(在我的情况下,第二页中的index.js,尽管第一页中也有index.js)-每个页的末尾使用app.METHODrouter.METHOD需要包含module.exports = router;

如果有人愿意,我会发布指向github模板的链接,该链接使用最佳实践实现了快速路由。让我知道

谢谢阿尼鲁德!很好的答案。

阳光Jim2020/03/24 17:59:16

如果您使用的是2.x以上版本的express,则必须像以下代码一样声明app.router。请尝试替换您的代码

app.use('/', routes);

app.use(app.router);
routes.initialize(app);

单击此处以获取有关app.router的更多详细信息

谢谢

注意:

app.router在Express 3.0+中已贬值。如果您使用的是Express 3.0+,请参阅下面的Anirudh答案。