在快速js 4中分离路由器文件时出错

时间:2016-07-26 06:27:08

标签: javascript node.js express

我是 Node Express 的新手,我喜欢 将路线功能分开到单独的文件中 ,但我总是得到错误。

我的 app.js 文件 -

var express = require('express');

var index = require('./Routes/index');

var app = express();

app.use(index);

app.listen(2000);

console.log("Server working at port 2000");

我的路线/ index.js

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

router.use(function(req,res,next){
  console.log("url "+req.url);
});

router.get('/',function(req,res){
  res.send("Hi is it working?");
});

module.export = router;

当我运行它时,说错误,如

app.use() requires middleware functions

如果我把

`app.use('/',index);` 
而不是 app.use(index); 然后我得到这样的错误

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

3 个答案:

答案 0 :(得分:1)

问题如评论中所述:

module.exports = router;

而不是:

module.export = router;

答案 1 :(得分:1)

因此,作为摘要(和正确的答案),您有两个问题:

<强>错字:

module.export = router;应为module.exports = router;

<强>中间件:

您的中间件应该调用next()将请求传递给下一个函数。有关详细信息,请查看the documentation

答案 2 :(得分:0)

我在问题中犯了两个错误

  1. 我有一个错字。在我放module.exports的行module.export中 (jonas

  2. 下一个错误是我需要将next();放在router.use()中间件函数中。因为我没有让next();知道在中间件功能之后要执行什么。我的意思是它不知道我的路线。 (javiercf