所以我尝试制作一个全栈项目。它有注册、登录、个人资料等 Controller 。
我所做的是手动要求每个 Controller ,然后根据请求使用它们。例如,我将有
app.use('/signup',signup);
app.use('/login',login);
app.use('/profile',profile);
但是,当我增加项目的复杂性时,将需要更多 Controller ,但手动输入所有内容并不是最佳实践。
我想要一个更通用的形式,只需一行即可完成所有工作:
app.use('whatever the link i got',load the corresponding controller);
也许解决方案会采用不同的形式。我怎样才能实现这个目标?我需要一些建议。
最佳答案
最简单的解决方案可能是将它们全部放在 controllers
目录中,然后执行以下操作:
const controllers = readdirSync(path.join(__dirname, 'controllers'))
controllers.forEach(controller => {
app.use(`/${controller}`, require(`./controllers/${controller}`))
})
只要你的路由和 Controller 被命名为相同的东西,这就很好用。如果您需要处理将烤肉串转换为驼峰式大小写,总有 lodash .
假设您使用的是express 4,您可以更进一步,将 index.js
放入 Controller 目录中。内部:
const express = require('express')
const router = express.Router()
const controllers = readdirSync(__dirname))
.filter(f => f !== 'index.js'))
controllers.forEach(controller => {
router.use(`/${controller}`, require(`./${controller}`))
})
module.exports = router
然后你就可以像这样使用路由器:
app.use('/', require('./controllers'))
关于javascript - 如何使用 Express 要求多个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45023624/