如何在Express.JS中优化路线?
我有很多路线:
app.all('/:controller', controller.init()); app.all('/:controller/:action', controller.init()); app.all('/:controller/:action/:par1', controller.init()); app.all('/:controller/:action/:par1/:par2', controller.init()); app.all('/:controller/:action/:par1/:par2/:par3', controller.init());
我可以优化这些路线吗?
不,你不能。 这不是你应该如何做路由。 路线应该明确界定有明智的uris。
例如我手写下面的路线
app.get(“/ blog”,controller.index);
app.get("/blog/new", controller.renderCreate); app.get("/blog/:postId/edit", controller.renderEdit); app.get("/blog/:postId/:title?", controller.view); app.post("/blog", controller.createPost); app.put("/blog/:postId", controller.updatePost); app.del("/blog/:postId", controller.deletePost);
这意味着您可以完全控制所需的URI。
非常build议你定义你想要的uris,然后把它们连接到你想要的任何控制器对象上。
这意味着你的uris保持漂亮,语义和完全控制。
目前我正在尝试完成像ASP.NET MVC路线,像这样做:
app.all('*', function(req, res) { //extract the route into an array var m_path = req.route.params.toString().split('/'); //require for a module with a dynamic name based on path info var controller = require('./controllers/' + m_path[1] + '.js'); //build a method name var fname = req.route.method + (m_path[2] || 'Index'); //if a exported method exists on the module, then use it, otherwise, create a new function var func = controller[fname] || function (){ //maybe use a 404 res.send('controller/method not found: ' + fname); }; //invoke the function func.call(this, req, res); });
在这个例子中,我有一个名为controllers的文件夹。 然后,我把所有的控制器里面的文件夹。 然后我可以做这样的事情:
路线:/用户/
js:controllers / users.js
//template: GET /users/ module.exports.getIndex = function(req, res) { res.send('get on index'); }; //template: POST /users/index module.exports.postIndex = function(req, res) { res.send('post on index'); }; //template: PUT /users/index module.exports.putIndex = function(req, res) { res.send('put on index'); }; //template: GET /users/custom module.exports.getCustom = function(req, res) { res.send('get on custom'); };
我修改了Jone Polvera的答案略有使用正则expression式:
app.all(/^(.+)\/(.+)/, function(req, res) { var controller = require('./routes/' + req.params[0] + '.js'); var fname = req.params[1]; var func = controller[fname] || function () { res.send('controller/method not found: ' + fname); }; func.call(this, req, res); });
我有一个名为路由的文件夹。 然后在路由中,我有一个名为admin.js的文件:
exports.posts = function(req, res) { ... }
所以这个URL / admin / posts被路由到那里。
- Express 4上的app.use('/ api')只呈现页面
- Firebase应用程序在localhost:5000 / / / app上运行
- 在哪里得到,在ExpressJS中定义的发布方法?
- 为什么不同的node.js会话共享variables?
- (node:6868) DeprecationWarning:`node –inspect –debug-brk`已被弃用
- 如何将用户连接到套接字
- 在使用Angular的单页面应用程序引擎时,依靠socket.io/express.io中的“disconnect”事件
- 以expressjs显示一个简单的图像
- Nodejs – 与vhostdynamic快速子域名