NodeJS + Express处理路由的替代方法

时间:2018-10-09 15:15:59

标签: node.js express

作为一个仍然掌握NodeJS和最佳实践的人,我想知道以下代码是否可以接受?

我测试这种方法并且不使用Express模板的主要原因是,我不想为每个路由文件都添加“ require”部分。例如,每条路线以及app.js都需要快递。

另外,通过我的方法,我能够扩展路由方法并对其进行更多处理。在某些情况下,如果文件夹结构有点偏离,npm将多次加载模块。用我的方法,我只是将包含模块数据的对象发送到依赖它的函数。


Express模板方法:

app.js:

let indexRouter = require('./routes/routes');
app.use('/', indexRouter);

routes.js:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

我的方法:

app.js:

let Routes = require('./modules/routes.js').Routes;
let routes = new Routes;
Routes = undefined;
routes.create(app, 'home.js');

routes.js:

var Routes = function () {};

Routes.prototype.create = function (app, route_file){
  //Load route file
  let newRoute = require('../routes/'.concat('',route_file)).newRoute;
  //Create instance of it
  let Routes = new newRoute;
  //Finally, create the routes
  Routes = Routes.create(app);

  //Cleaning
  newRoute = undefined;
  Routes = undefined;
};

exports.Routes = Routes;

home.js:

var newRoute = function () {};

newRoute.prototype.create = function (app) {
  app.get('/home', sayHi);

  function sayHi(req, res){
    res.send('Hello World!');
  };
};

exports.newRoute = newRoute;

0 个答案:

没有答案