在通过express --view=pug myapp
命令安装的快速应用中,我想动态加载路由。我已经尝试过here中的代码,但是在TypeError: Cannot read property 'apply' of undefined
中收到错误消息express\lib\router\index.js:635
。因此,我创建了以下代码:
function processRoutePath(route_path) {
const fs = require('fs');
fs.readdirSync(route_path).forEach(function(file) {
let filepath = route_path + '/' + file;
fs.stat(filepath, function(err,stat) {
if (stat.isDirectory()) {
processRoutePath(filepath);
} else {
let name = file.replace('.js', '');
if (name === 'index') {
app.use('/', require(filepath));
} else {
app.use('/' + name, require(filepath));
}
}
});
});
}
processRoutePath('./routes');
代码位于// catch 404 and forward to error handler
中app.js
行的上方,这已生成...我没有收到任何错误,但是当我在Web浏览器中运行它时,却得到404结果。我猜想this的方法行不通,因为在路由文件中,我使用express.Router()
的实例来调用控制器,例如
let express = require('express');
let router = express.Router();
let landing = require('../controllers/landing');
router.get('/', landing.get_landing);
module.exports = router;