在全局中重定向所有尾部斜杠 [英] Redirect all trailing slashes globally in express

查看:272
本文介绍了在全局中重定向所有尾部斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js和Express,我有以下路由:

  app.get('/' function(req,res){
locals.date = new Date()toLocaleDateString();

res.render('home.ejs',localals);
} );

函数lessonsRouter(req,res,next)
{
var lesson = req.params.lesson;
res.render('lessons /'+ lesson +'.ejs',locals_lessons);
}

app.get('/ lessons /:lesson *',lessonsRouter);


函数viewsRouter(req,res,next)
{
var controllerName = req.params.controllerName;
res.render(controllerName +'.ejs',locals_lessons);
}
app.get('/:controllerName',viewsRouter);我有一个 Disqus


$一个>我的课程页面上的小部件,我注意到一个奇怪的行为,当去 myapp.com/lessons myapp.com/lessons/ 我得到两个不同的页面(其中有一个我以前在Disqus中添加的评论,另一个没有评论)。



有没有办法封存我所有的网址,没有拖尾?我试图添加 strict routing 标志来表达,但结果是一样的



谢谢

解决方案

尝试添加一个中间件;

  app.use(function(req,res,next){
if(req.url.substr(-1)=='/'& req.url.length> 1)
res.redirect(301,req.url.slice(0,-1));
else
next();
});


I am using Node.js and Express and I have the following routing :

app.get('/', function(req,res){
    locals.date = new Date().toLocaleDateString();

    res.render('home.ejs', locals);
});

function lessonsRouter (req, res, next)
{
    var lesson = req.params.lesson;
    res.render('lessons/' + lesson + '.ejs', locals_lessons);
}

app.get('/lessons/:lesson*', lessonsRouter);


function viewsRouter (req, res, next)
{
    var controllerName = req.params.controllerName;
    res.render(controllerName + '.ejs', locals_lessons);
}
app.get('/:controllerName', viewsRouter);

I have a Disqus widget on my lessons pages and I have noticed a strange behavior that when going to myapp.com/lessons and myapp.com/lessons/ I get two different pages (on of them had a comment I previously added in Disqus and the other one doesn't have a comment).

Is there a way to "canonize" all of my urls to be without trailing slashes ? I have tried to add the strict routing flag to express but the results were the same

Thanks

解决方案

Try adding a middleware for that;

app.use(function(req, res, next) {
   if(req.url.substr(-1) == '/' && req.url.length > 1)
       res.redirect(301, req.url.slice(0, -1));
   else
       next();
});

这篇关于在全局中重定向所有尾部斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆