我目前正在使用app.get来解决我工作的网站的URL请求。我正在使用app.get完成以下任务:
www.site.com/html/contact.html
而是翻译成
www.site.com/contact
我通过以下方式使用app.get:
app.get('/team',function(req,res){res.sendfile('team.html',{'root':'./html'});});
app.get('/yada',function(req,res){res.sendfile('yada.html',{'root':'./html'});});
app.get('/home',function(req,res){res.redirect('/');});
app.get('*',function(req, res){res.redirect('/');});
所有这些都非常出色,我的问题是也许JavaScript特有的。我想要的是这样的:
app.get({
'/team',function() ...,
'/home',function() ...,
'/yada',function()...
});
与我的操作类似:
var express = requires('express'),
app = express();
这可能吗?
更新
我已经将errorHandler与CuriousGuy的解决方案结合在一起,该解决方案非常有效:
errorHandler = function(err,req,res,next){res.redirect('/');};
app.get('/:page',function(req,res){res.sendFile(req.params.page + '.html',{'root':'./html'});}).use(errorHandler);
尽管我确实必须更改文件名以适合此路由方法,但到目前为止,它的效果很好。
最佳答案
您可以执行以下操作:
var routes = {
'/team': function() {},
'/home', function() {}
};
for (path in routes) {
app.get(path, routes[path]);
}
尽管您应该小心进行此类微优化。使用标准语法可以使您的代码清晰易读。在牺牲易读性的同时竭尽全力使代码“更小”并非总是一件好事。
关于javascript - Node.js Express紧凑脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26686379/