在nodejs中重写url

时间:2016-02-05 11:47:16

标签: node.js middleware

我希望在我的应用程序中有一个默认控制器和默认操作,这样如果用户来到root,他将被提供给相应的页面。 为此,我制作了一个中间件

module.exports = function (controller, action) {
  return function (req, res, next) {
    // remove any trailing slashes
    req.originalUrl = req.originalUrl.replace(/\/$/, "");
    // provide default controller
    if (!req.params.controller) {
      req.originalUrl = '/' + controller;
    }
    // provide default action
    if (!req.params.action) {
      req.originalUrl = req.originalUrl + '/' + action;
    }
    console.log(req.originalUrl); // gives me expected result
    next();
  }
}

这是我的应用代码:

var router=require(./router())
app.use('/:controller?/:action?',urlMaker(config.defaultController,config.defaultAction));
app.use('/',router);

这是路由器代码:

var express = require('express');
var globals = require('../globals');

function getRouter() {
  var router = express.Router();
  var controllerList = globals.getController();
  console.log("Creating routes for available controllers");

  for (var name in controllerList) {
    //start creating routes for available controllers
    router.get('/' + name + '/:action', function (req, res, next) {
      console.log("router reached");
      var action = req.params.action;
      controllerList[name][action](req, res);
    });
    console.log("Created route for " + name);
  }

  router.get('/test', function () {
    console.log("hello");
  });

  return router;
}

module.exports = getRouter;

我做错了什么。问题是路由器没有收到动作名称。怎么做?

1 个答案:

答案 0 :(得分:0)

这个简单的架构可以很好地定义router.jsmiddlewares.jsapp.js

middlewares.js

function getMiddleware(v1, v2) {
  return function (req, res, next) {
    // whatever, you can use v1 and v2 as you wish
    next();
  }
}

module.exports = getMiddleware;

router.js

var express = require('express');

function getRouter(v3) {
  var router = express.Router();
  router.get('/', function (req, res) {
    // whatever, here you have v if you wish
    res.send('Hello ' + v);
  });
  return router;
}

module.exports = getRouter;

app.js

var middleware = require('./middlewares');
var router = require('./router');
var express = require('express');

// ----
var v1 = v2 = v3 = 42;
// -----
var app = express();

app.use(middleware(v1, v2));
app.use('/', router(v3));
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

一旦这个简单的应用程序运行,我就会选择“自动路由器定义”(for循环)。无论如何,我建议不要在function循环中定义for