我有appController,userController和noteController。我想将userController和noteController导入到appController中
首先,这里是noteController
module.exports = {
index: (req, res) => {
Note.find({}).sort({
time: -1
}).exec((err, notes) => {
if (err) throw err;
res.send(notes)
});
}
}这是appController
const noteController = require('./noteController');
const userController = require('./userController');
module.exports = {
show: (req, res) => {
noteController.index((err, notes) => {
if (err) throw err;
res.render('index', {
notes: notes
});
});
}
}我开始这个项目时只使用了notesController,最终在Node中学习了CRUD,但我在这里有点困惑。在我的appController中,我想为笔记建立索引,并检查用户是否已登录。如果我在这里做了糟糕的编码练习,请让我知道。
发布于 2017-08-12 16:07:56
根据应用程序的大小,肯定有不同的方法可以实现您正在考虑的内容。也就是说,我经常看到的一般约定是
1)为您的登录端点创建用户控制器,例如/api/login
2)创建中间件来保护任何需要用户登录的路由
3)将用户id存储在request对象中( #2中的中间件执行此检查,并将问题id存储在request对象中,以便您可以解码用户id,并使用它向数据服务查询属于该用户的笔记)
也就是说,我假设您的应用程序可能不需要朝这个方向驱动。所以这也可以用在你身上
const userController = (req, res) => {
/* Handle your logic here
Check that the user credentials match what is in DB
Check if the user has notes.
This might be two different queries to your DB(User and Notes tables(or collections)) depending on how you structure your schema.
You can now respond with the user `specific` notes e.g `res.render('notes', {notes: notes})`
*/
}希望这能有所帮助!
https://stackoverflow.com/questions/45647380
复制相似问题