NodeJS URL重写中间件组件
var connect = require("connect");
var url = require("url");
//先使用rewrite中间件组件基于缩略名重写URL,然后将控制权转交给showPost组件
var app = connect()
.use(rewrite)
.use(showPost)
.listen(3000);
var path = url.parse(req.url).pathname;
function rewrite(req,res,next){
var match = path.match(/^\/blog\/posts\/(.+)/);//只针对/blog/posts 请求执行查找
if(match){
//假想方法findPostIdBySlug
findPostIdBySlug(match[1],fuction(err,id){
if(err) return next(err);
if(!id) return next(new Error("User not found"));
//重写req.url属性,以便后续中间件可以使用真实的ID
req.url = "/blog/posts/" + id;
next();
});
}else{
next();
}
}