简体   繁体   中英

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

I am a newbie to Express js. I am following the tutorials from tutorials point

I tried implementing the examples given there but I keep getting the following error

/home/krishna/.nvm/versions/node/v5.0.0/bin/node /home/krishna/self/projects/projects/Node/nativebag/bin/www
/home/krishna/self/projects/projects/Node/nativebag/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 (/home/krishna/self/projects/projects/Node/nativebag/node_modules/express/lib/router/index.js:458:13)
    at EventEmitter.<anonymous> (/home/krishna/self/projects/projects/Node/nativebag/node_modules/express/lib/application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (/home/krishna/self/projects/projects/Node/nativebag/node_modules/express/lib/application.js:217:7)
    at Object.<anonymous> 

(/home/krishna/self/projects/projects/Node/nativebag/app.js:25:5)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)

Process finished with exit code 1

I've looked for solutions online but wasn't able to solve it.

Here is my code:

Index.js

var express = require('express');
var app = express();

var things = require('./things.js');

app.use('/things', things);
app.listen(3000);

things.js

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

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

// POST hello world
router.post('/', function (req, res, next) {
    res.send("Hello World");
});

module.exports = router;

Could some one point the error?

thanks.

It was essentially and issue of change in version of Express. Below is the code that I changed and now it is working fine.

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

var things = require('./things.js');

router.use('/things', things);

module.exports = router;
// app.listen(3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM