如何在Express.js中的控制器之间共享通用逻辑? [英] How to share the common logic between controller in Express.js?

查看:84
本文介绍了如何在Express.js中的控制器之间共享通用逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用快递来建立我的网站,我有一个特殊的要求.我将路由器设置如下:

I had used the express to build my website, and I have a special require.I had set the routers as follow:

/* home */
app.get('/', function (req, res, next) {
    homeRacingHandle(req,res);
});

/* racing list */
app.get('/racing',function (req, res, next) {
    homeRacingHandle(req,res);
});

主页

There is just a few differents between the home page and the racing list page. My method to process the common logic is like above.And the homeRacingHandle function according the variable isHome to decide which page to render.

    var location = req.path.split('?').toString();
    var isHome = location==='/' && true || false;

此方法对我有用.但是我不知道是否有一个很好的处理方法.还有其他最佳实践吗?

This method works for me.But I don't know wether is a good way to process.Are there any other best practice?

推荐答案

您可以使用curring来简化

You could use currying to simplify this

curryHomeRacing = require('./handler');

/* home */
app.get('/', curryHomeRacing('home'));

/* racing list */
app.get('/racing', curryHomeRacing('racing'));

在另一个文件handler.js中

In another file handler.js

//in handler.js

module.exports = function curryHomeRacing(route){
    return function(req, res) {
        homeRacingHandle(req, res, route);
    };
}

function homeRacingHandle(req, res, route) {
    if (route === 'home') {
        //do home stuff
    } else if (route === 'racing') {
        //do racing stuff
    }
}

这篇关于如何在Express.js中的控制器之间共享通用逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆