express auto router
发布于 8 年前 作者 NextZeus 3777 次浏览 来自 分享
var express = require('express');
var app = express();
var router = express.Router();

//设置 所有/users路径的URL 都会通过
app.use('/users',router);

// /users/list
router.get('/list', function (req, resp) {
    resp.end('/users/list');
});
//自动加载exports接口称为route
var loadRoutes = function(){
    var dirName = __dirname;
    var routesPath = path.join(dirName,'/routes');
    var files = fs.readdirSync(routesPath);
    for(var i = 0; i < files.length; i ++){
        var filePath = path.join(routesPath,files[i]);
        if(!fs.statSync(filePath).isDirectory()){
            var model = require(filePath);
            for(var key in require(filePath)){
                if(typeof(model[key]) ==  'function'){
                    router.post('/' + key,model[key]);//关键点
                }
            }
        }
    }
};
loadRoutes();
回到顶部