我想知道如何在控制器之间进行通信

点击电子邮件中的authentication链接,使用电子邮件authentication来实现成员资格方法时,我想在服务器内部确认令牌后调用用户创buildAPI。

//emailcontroller.js router.get('/register/token', function(req, res) { // check token if(check(req.params.token)) { request('http://localhost:8080/api/user', function(data) { }); } }); //usercontroller.js router.post('/api/user', function(req, res) { var user = new User(); user.userId = req.body.userId; user.userPw = req.body.userPw; user.save(); }); 

在点击电子邮件中的authentication链接来实现使用电子邮件authentication的成员资格方法时,我想在服务器内部确认令牌后调用用户创buildAPI。

如上所述,电子邮件控制器和用户控制器被分开,并且每个被路由。 我想模块化代码,以便我想调用现有的用户创buildAPI来将其用于通用目的,而不是为特定控制器创build和导出常用函数。

 /*I do not want to implement it this way.*/ //emailController.js router.get('/register/token', function(req, res) { // check token if(check(req.params.token)) { userContoller.createUserFromEmail(userId, userPw); } }); //userController.js exports.createUserFromEmail = function(userId, userPw) { var user = new User(); user.userId = userId; user.userPw = userPw; user.save(); } 

但是,在很多例子中,我从来没有见过控制器之间的通信。 所以我不知道我认为是对的。 相反,我认为在服务器上调用API的代价可能会更高。

我想知道控制器之间通信的正确模式。 请记住,提出问题时只有堆栈溢出。

你有正确的想法作为独立的函数(或类)公开你的APIfunction。 为了避免重复,只需从你的路由处理程序中调用你的内部方法。 所以在你的例子中:

 router.post('/api/user', function(req, res) { createUserFromEmail(req.body.userId, req.body.userPw); }); 

在我自己的项目中,我使用类来创build我的API。 首先我定义一个只有function的类,然后在路由处理程序中公开方法:

 export default class User { read() { } create() { } update() { } delete() { } } const user = new User(); router.get('/user/:id', (req, res) => user.read(req.params.id)); router.post('/user', (req, res) => user.create(req.body.data)); router.put('/user/:id', (req, res) => user.update(req.params.id, req.body.data)); router.delete('/user/:id', (req, res) => user.delete(req.params.id)); 

这应该让你知道你可以做什么。 您可以编写自定义中间件和类装饰器来减less样板。

从你的问题我的理解:你想在内部validation在查询parameter passing的令牌之前,在用户控制器做任何事情。

我相信你使用快递,而快递来中间件 。

从文档:

中间件function是可以访问请求对象(req),响应对象(res)和应用程序请求 – 响应周期中的下一个中间件function的函数。 下一个中间件函数通常用名为next的variables表示。

我通常做的和一般的良好做法是,通过create user api的令牌并附加到电子邮件正文。

例如:

api/user?token=somerandomstringloremispum

路线文件:

router.post('/user', validateEmail, userController.create);

这里validateEmail是一个middleware函数,将在userController create方法之前被调用。

现在在你的validateToken方法中,你可以简单地validation你的令牌:

 function validateEmail (req, res, next) { if(!valid(req.query.token)) { //return with appropriate invalid token msg using res.json() or however you like } // if validated call `next middleware` like so: next(); // this will allow `create` method of userController be invoked }