321

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

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

Datise
  • 3,683
  • 2
  • 11
  • 12

16 Answers16

1477

In any one of your js pages you are missing

module.exports = router;

Check and verify all your JS pages

Anirudh
  • 15,107
  • 2
  • 14
  • 26
  • 4
    @Anirudh Mind describing the reason for the error as well – sac Dahal Oct 05 '16 at 16:45
  • @Anirudh, thanks it was helpful but how to export router here in ES6? simple `export {router}` also gives that error – Adil May 11 '17 at 05:57
  • 4
    @adi http://stackoverflow.com/questions/38550979/importing-exporting-the-express-router-using-es6-import-export-keywords-and-ba here you go :) – Anirudh May 11 '17 at 09:12
  • Worth noting this is typically at the very end of you js page – AndrewLeonardi Sep 13 '17 at 01:11
  • 7
    well i was missing an `s` at end :| – Muhammad Umer Oct 22 '17 at 13:29
  • time to find express linting – Muhammad Umer Oct 22 '17 at 13:29
  • What if I would like to export both the `router` and some other function that I want to use externally in other files? – mesllo Jun 20 '18 at 09:51
  • Great. It works well for me. I got a typo module.export = router; I did it without (s) at the end of export. Holy heck, one hour of my life. – Tuan Phan Jul 08 '19 at 11:10
  • I didn't understand why we need to export the `router` when we are doing `const router = express.Router()` on every page we are using it? – darKnight Sep 08 '22 at 07:41
  • I had a similar problem despite having ```module.exports=router``` at the bottom of my file I was still getting the same error. After taking a nap I realized that I imported the router like this ```const {deviceRouter} = require('./Routes/devices.js');``` instead of this ```const deviceRouter = require('./Routes/devices.js');```. I don't know why it didn't work the previous way but I learned something new. – Alex Antoine Feb 15 '23 at 13:57
138

Simple solution if your are using express and doing

const router = express.Router();

make sure to

module.exports = router ;

at the end of your page

Parikshit Hooda
  • 1,471
  • 1
  • 8
  • 5
54

In my case, I wasn't exporting the module. module.exports = router;

S. Hesam
  • 5,266
  • 3
  • 37
  • 59
Usama Tahir
  • 1,235
  • 12
  • 14
33

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

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

Striped
  • 2,544
  • 3
  • 25
  • 31
27

You are missing router exports module and that is the reason why this error is present.

use module.exports = router; and that would work

Anish Jain
  • 509
  • 5
  • 12
19

You just have to export your router using module.exports = router;

Rahul More
  • 514
  • 6
  • 10
8

check your routes.js file

example my routes.js

    const express = require('express')
    const router = express.Router()
    
    const usersController = require('../app/controllers/usersController')
    const autheticateuser = require('../app/middlewares/authentication')
    
    router.post('/users/login', autheticateuser, usersController.login)
    router.post('/users/register', autheticateuser, usersController.register)
      

check end of routes.js

module.exports = router

if not there add and module.exports = router run again


If your Error is : "TypeError: Route.post() or Route.get() requires middleware function but got a Object"

goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers

const User = require('../models/user')
const express = require('express')
const router = express.Router()



module.exports.register = (req, res) => {
    const data = req.body
    const user = new User(data)
    user.save()
        .then((user) => {
            res.send(user)
        })
        .catch((err) => {
            res.json(err)
        })
}

in routes.js i given two routes but in controllers i missed to define route for

router.post('/users/login')

this will make error **

"TypeError: route.post() requires middleware function but got a Object"

**

K23raj
  • 331
  • 4
  • 3
6

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;

antzshrek
  • 9,276
  • 5
  • 26
  • 43
Michael Staton
  • 109
  • 1
  • 4
5

I got this error because I had used a series of files like this:

app.use('/api/someName1', someName1);
app.use('/api/someName2', someName2);
...
app.use('/api/someNameN', someNameN);

The issue was although I had properly declared it, one of the files was still empty. Just leaving it here in case someone else too does this mistake. To stop wasting time on some of the other solutions since it was the same error message that gets displayed for all.

Happy hacking!

IronmanX46
  • 558
  • 7
  • 16
2

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.

antzshrek
  • 9,276
  • 5
  • 26
  • 43
2

For me, following worked.

instead of this

app.use('/', routes);

use

app.use('/', () => routes);

or

app.use('/', function(){routes});
oms
  • 105
  • 1
  • 2
1

Check your all these file:

var users = require('./routes/users');

var Users = require('./models/user');
var Items = require('./models/item');

Save properly, In my case, one file was missed and throwing the same error

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
Coresumo
  • 26
  • 3
0

In my case I have written app.use('view engine', 'ejs'); instead of app.set('view engine', 'ejs'); to set ejs as the view engine.

Wasit Shafi
  • 854
  • 1
  • 9
  • 15
0

In my case, the problem was that I was requiring the wrong file to pass as a middleware ( app.use(nameOfFile) ). Once I imported the correct one, the error went away.

Esteban
  • 101
  • 3
  • 6
0

In my case I was exporting the middleware function as exports.function_name, changing this to a call back function and doing module.exports = function_name; solved the issue for me.

Moreover in your routes you could do,

const function_name = require('./middlewares/middleware_file_name');
router.use('/protected_route', function_name);
first
  • 616
  • 1
  • 7
  • 13
0

In my case I mistakenly read route file without using require:|

Amin
  • 31
  • 3
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33455763) – Insane Skull Dec 24 '22 at 08:58