我正在尝试设置节点项目,我想在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
如何以这种方式配置设置有什么问题?
谢谢
答案 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);
应该有用......