NodeJS + Express:如何以不同的方式制作类似的(通过掩码)URL路由?

时间:2012-09-21 09:03:51

标签: regex node.js url routing express

我正在写一个小组博客。我的应用程序中有一个非常具体的路由,我遇到了一些麻烦。为了说清楚,我已经写了一个简单的演示应用程序:

//pathtest.js
//creating §
var express = require('express');
var app = express();
//setting express app
app.configure(function() {
    app.use("/static", express.static(__dirname + '/static'));
    app.use(express.bodyParser());
});
app.listen(3000);


//serving hashtag requests like /music, /photo, /personal, etc. 
app.get('/music', function(req, res) {
    res.send('music');
});
app.get('/photo', function(req, res) {
    res.send('photo');
});
app.get('/personal', function(req, res) {
    res.send('personal');
});
//... and +20+ more various hashtags

//serving SUBCATEGORIES for hashtags
//e.g.: /music/rock, /photo/digital
app.get('/:hashtag/:subcat', function(req, res) {
    res.send('Subcategory ' + req.params.subcat + ' for hashtag ' + req.params.hashtag);
});


//SINCE THIS LINE IT DOESNT WORK 'CAUSE EVERY OF THE FOLLOWING REQUESTS CAN BE SERVED WITH ONE OF 4 UPPER CASES :(

//serving usernames of our service
//We put it apecially AFTER SERVING HASHTAGS as they have similar mask, first should be checked if it's hashtag
//e.g.: /bob_johnson
app.get('/:user', function(req, res) {
    res.send('Welcome, ' + req.params.user + '!');
});

//serving single post service
//e.g.L: /163728
app.get('/:postid', function(req, res) {
    res.send('This is post #' + req.params.postid);
});

//serving post commenting
//e.g.: /35345345/comment
app.get('/:postid/comment', function(req, res) {
    res.send('Edit post #' + req.params.postid);
});

行后

//SINCE THIS LINE IT DOESNT WORK 'CAUSE EVERY OF THE FOLLOWING REQUESTS CAN BE SERVED WITH ONE OF 4 UPPER CASES :(

无法提供任何请求。我认为这是因为以下每一种情况都可能与上层路线一起服务。实际上,正如我所说,Node,serve / bob和/ 234234没有实际的区别,但是这样的URL应该单独提供!一个 - 显示用户个人资料,第二个 - 显示帖子。和/ 23423423 /评论应该作为帖子#23423423的评论,但/ bob / comment应该被忽略并重定向到/ bob。但是/ music - 不是用户名,它是标签,而/ music / comment - 不是对#music帖子的评论,而是对标签音乐等的子类别。这个列表可以继续......

主要问题:如何以不同的方式使Node.JS路由类似(通过掩码)URL?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以在路线中使用RegExp。

尝试:

//serving single post service
//e.g.L: /163728
app.get('/:postid(\d+)', function(req, res) {
    res.send('This is post #' + req.params.postid);
});

//serving usernames of our service
//e.g.: /bob_johnson
app.get('/:user', function(req, res) {
    res.send('Welcome, ' + req.params.user + '!');
});

或者:

//serving single post service
//e.g.L: /163728
app.get(/^\/(\d+)$/i, function(req, res) {
    res.send('This is post #' + req.params[0]);
});

//serving usernames of our service
//e.g.: /bob_johnson
app.get('/:user', function(req, res) {
    res.send('Welcome, ' + req.params.user + '!');
});