首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nodejs将控制器导入控制器

Nodejs将控制器导入控制器
EN

Stack Overflow用户
提问于 2017-08-12 14:47:05
回答 1查看 651关注 0票数 0

我有appControlleruserControllernoteController。我想将userControllernoteController导入到appController

首先,这里是noteController

代码语言:javascript
复制
module.exports = {
    index: (req, res) => {
        Note.find({}).sort({
            time: -1
        }).exec((err, notes) => {
            if (err) throw err;
            res.send(notes)
        });
    }
}

这是appController

代码语言:javascript
复制
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中,我想为笔记建立索引,并检查用户是否已登录。如果我在这里做了糟糕的编码练习,请让我知道。

EN

回答 1

Stack Overflow用户

发布于 2017-08-12 16:07:56

根据应用程序的大小,肯定有不同的方法可以实现您正在考虑的内容。也就是说,我经常看到的一般约定是

1)为您的登录端点创建用户控制器,例如/api/login

2)创建中间件来保护任何需要用户登录的路由

3)将用户id存储在request对象中( #2中的中间件执行此检查,并将问题id存储在request对象中,以便您可以解码用户id,并使用它向数据服务查询属于该用户的笔记)

也就是说,我假设您的应用程序可能不需要朝这个方向驱动。所以这也可以用在你身上

代码语言:javascript
复制
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})`
  */
}

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45647380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档