2016-02-05 74 views
0

我想在我的應用程序中使用默認控制器和默認操作,以便如果用戶進入root用戶,他將被提供相應的頁面。 對於我做了一箇中間件在nodejs中重寫url

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; 

我在做什麼錯。問題是路由器沒有收到操作名稱。怎麼做 ?

回答

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循環)。無論如何,我建議您不要在for循環內定義function

+0

當我爲目錄硬編碼一個路由時,即使在重寫之後它仍然執行正常。但是當我嘗試重寫URL時,在for循環中創建的路由不起作用。然而,他們的工作,如果我直接輸入正確的url,如localhost:3000 /目錄/索引工作正常,但不適用於本地主機:3000 –