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;
我在做什麼錯。問題是路由器沒有收到操作名稱。怎麼做 ?
當我爲目錄硬編碼一個路由時,即使在重寫之後它仍然執行正常。但是當我嘗試重寫URL時,在for循環中創建的路由不起作用。然而,他們的工作,如果我直接輸入正確的url,如localhost:3000 /目錄/索引工作正常,但不適用於本地主機:3000 –