Express js - 在单独的文件中使用路由

时间:2017-10-31 11:52:44

标签: javascript node.js express

我正在尝试设置节点项目,我想在routes.js中放置一个文件routes/routes.js,在controllers/目录中放置一个控制器文件。

所以,例如,我有UserController这样:

var index = () =>
{
  console.log("User Index");
};
var getUser = (id) => {
  console.log("User by id " + id);
};

module.exports =
{
  index,
  getUser
}

routes.js我有这个:

    var express = require('express');
var routes = express.Router();
var users = require('../controllers/usersController');


routes.route('/')
  .get(users.index);

routes.route('/user/:userId')
  .get(users.getUser);


module.exports=
{
  routes
};

index.js我以这种方式设置:

    let express = require('express');
let app = express();
let routes = require('./routes/routes');

app.set("views", './views');
app.set("view engine", 'jade');


app.use(express.static(__dirname + '/public'));

app.use('/', routes.index);
// launch ======================================================================
app.listen(9001);

当我尝试运行服务器时出现此错误:

.../node_modules/express/lib/router/index.js:458
  throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
  ^
  TypeError: Router.use() requires a middleware function but got a undefined

如何以这种方式配置设置有什么问题?

谢谢

2 个答案:

答案 0 :(得分:3)

您的userController将是这样的。

 module.exports = {
        index: (req, res) => {
            console.log("User Index");
        },
        getUser: (req, res) => {
            console.log("User by id " + req.params.id);
        }
    }

您的路线文件将是这样的

var express = require('express');
var routes = express.Router();
var users = require('../controllers/usersController');

routes.get('/', user.index);
routes.get('/user/:userId', user.getUser);

module.exports = routes;

你的索引文件将是这样的

let express = require('express');
let app = express();
let routes = require('./routes/routes');

app.set("views", './views');
app.set("view engine", 'jade');


app.use(express.static(__dirname + '/public'));
app.use('/', routes);

app.listen(9001);

答案 1 :(得分:1)

routes.js替换:

module.exports=
{
  routes
};

module.exports = routes;
index.js

中的

app.use('/', routes.index);app.use('/', routes);

应该有用......