TypeError: Router.use() requires middleware function but got a Object

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

There have been some middleware changes on the new version of express and I have made some changes in my code around some of the other posts on this issue but I can't get anything to stick.

We had it working before hand but I can't remember what the change was.

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. (/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; 

It appears the answer to this question has changed for versioning reasons. Thanks to Nik

回答1:

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes); 

with

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

Please click here to get more details about app.router

Thanks



回答2:

In any one of your js pages you are missing

module.exports = router; 

Check and verify all your JS pages



回答3:

I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.

I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.

My typical file structure is as follows:

/lib  /routes 

---index.js (controls the main navigation)

/page-one    /page-two         ---index.js 

(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHOD or router.METHOD needs to have module.exports = router; at the end)

If someone wants I will post a link to github template that implements express routing using best practices. let me know

Thanks Anirudh!!! for the great answer.



回答4:

I was getting the same error message but had a different issue. Posting for others that are stuck on same.

I ported the get, post, put, delete functions to new router file while refactoring, and forgot to edit the paths. Example:

Incorrect:

//server.js app.use('/blog-posts', blogPostsRouter);  //routers/blogPostsRouter.js router.get('/blog-posts', (req, res) => {   res.json(BlogPosts.get()); }); 

Correct:

//server.js app.use('/blog-posts', blogPostsRouter);  //routers/blogPostsRouter.js router.get('/', (req, res) => {   res.json(BlogPosts.get()); }); 

Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;



回答5:

I think you have not exported your router.

module.exports = router;  //what ever your export router name. 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!