我希望在风帆将页面呈现为html之前调用单独的函数(例如服务函数)。请参考下面的控制器代码......
var MYController = {
index: function(req, res, next) {
req.flash("error", "Testing hello world");
MyCustomServices.myFunction( req, res );
res.view();
}
}
只需添加我的服务功能api / services / MyCustomServices.js
exports.myFunction = function( req, res ){
Test.findOne({ code : "CODE" }, function(err, resp) {
if ( resp ) {
res.locals.TEST = resp;
}
});
var msg = req.flash('error');
res.locals.ERROR = msg.length>0 ? msg : "" ;
};
在这种情况下,在执行res.view之前,当我调用MyCustomServices.myFunction(req,res)时,还有另一个进程要运行;
问题是,每次我有res.view()函数调用时,我都需要在所有控制器的操作中添加这一行。
我试图添加这个MyCustomServices.myFunction(req,res);在express.js中,它似乎没有按预期工作。但我想,它应该是明确的,只是我不知道我需要添加哪些代码。
MyCustomServices.myFunction(req,res)中的内容是:
有人对此有所了解吗?
答案 0 :(得分:0)
如果您需要在res.view
执行完毕后致电Service
,可以从控制器中删除res.view
,并将其放入服务中:
var MYController = {
index: function(req, res, next) {
req.flash("error", "Testing hello world");
MyCustomServices.myFunction( req, res );
//res.view();
}
}
exports.myFunction = function( req, res ){
Test.findOne({ code : "CODE" }, function(err, resp) {
if ( resp ) {
res.locals.TEST = resp;
res.view(); //TADA
}else {
/* Handle Error */
}
});
var msg = req.flash('error');
res.locals.ERROR = msg.length>0 ? msg : "" ;
};
答案 1 :(得分:0)
两个选项
为您的服务添加回调
var MYController = {
index: function(req, res, next) {
req.flash("error", "Testing hello world");
MyCustomServices.myFunction( req, res, function(){
return res.view();
} );
}
}
exports.myFunction = function( req, res, cb ){
Test.findOne({ code : "CODE" }, function(err, resp) {
if ( resp ) {
res.locals.TEST = resp;
return cb()
}
});
};
- 或(根据您的评论) -
您可以为应用添加自定义响应处理程序。查看http://sailsjs.org/#/documentation/concepts/Custom-Responses
您可以使用res.ok()替换res.view(),然后使用您的服务修改api / responses / ok.js。
或者如果你不想搞砸ok.js,你可以创建自己的回复