表达错误:抛出新的TypeError(' Router.use()需要中间件函数但得到了' + gettype(fn));

时间:2017-05-17 08:20:08

标签: javascript node.js express

我是Express js的新手。我正在关注song from the super duper anime Clannad

中的教程

我尝试实现那里给出的示例,但我不断收到以下错误

/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

我在线寻找解决方案,但无法解决。

这是我的代码:

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;

有人可以指出错误吗?

感谢。

1 个答案:

答案 0 :(得分:0)

本质上是Express版本的变化问题。 下面是我更改的代码,现在它正常工作。

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

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

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

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