Node.js Express紧凑脚本
我目前正在使用app.get来parsing我工作的网站的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();
这可能吗?
UPDATE
我已经将CuriousGuy的解决scheme并入了一个errorHandler,
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]); }
虽然你应该小心这样的微观优化。 使用标准语法保持您的代码清晰可读。 为了使代码“更小”而牺牲可读性,并不总是一件好事。
如果你所需要的只是编写更less的代码来制作“non-dot-html”的URL,你可以使用正则expression式:
app.get(/^\/(team|yada|contact)\/?$/, function(req, res) { res.sendfile('./html/' + req.params[0] + '.html'); }); app.get('*',function(req, res){res.redirect('/');});
team|yada|contact
以上team|yada|contact
部分是由|
分隔的页面列表 。 您可以根据需要在此列表中包含尽可能多的页面,但请记住,正则expression式可能会降低应用程序的性能。
更新:
编码一段时间后,我发现一个没有正则expression式的解决scheme:
app.get('/:page', function(req, res, next) { if (['team', 'yada', 'contact'].indexOf(req.params.page) === -1) { return next(); } res.sendfile('./html/' + req.params.page + '.html'); });
只需添加你需要的页面['team', 'yada', 'contact']
数组。
更新2:
为了演示正则expression式的性能,我写了一个小脚本,它以两种不同的方式创build相同的东西 – 第一种情况是用正则expression式replacestring,而在另外一种情况下,不用正则expression式:
var sentence = 'In order to consolidate your success we advise you to continue your work'; for (var i = 0; i < 1000000; i++) { //case 1: regular expressions replacement var word = sentence.replace(/success/, 'SUCCESS'); //case 2: simple string replacement //var word = sentence.replace('success', 'SUCCESS'); }
并使用以下命令(在Linux机器上)运行两次:
time node test.js
当案例1未注释,案例2评论我得到约0m1.106s
,否则 – 0m0.585s
。 所以我们有正则expression式运行比非正则expression式相当慢两倍。 这就是为什么build议在性能敏感的应用程序中尽量避免使用正则expression式。
我希望我回答你的问题,并为我的英语感到难过:)
- 错误:在Ubuntu上发布应用程序时,ENOENT,没有这样的文件或目录'/ var / www / html / views
- ExpressJS会话尽pipe活动即将到期
- 如何使用node.js(express.js)重新发送带有上传文件的post multipart / form-data表单到不同的服务器?
- 如何将http服务器与express对象绑定到一个特定的ip地址?
- 将app.js中的params传递给route.js
- 使用Express和Nodejs进行路由时出现404错误
- Express.js:是否有可能像res.render一样将对象传递给redirect?
- 如果使用授权承载令牌,则为400错误请求
- 以ui-grid格式化页脚值