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

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

问题描述

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

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);

我的课程页面上有一个 Disqus 小部件,我注意到在访问 myapp.com/lessons 时出现了一种奇怪的行为myapp.com/lessons/ 我得到两个不同的页面(其中一个有我之前在 Disqus 中添加的评论,另一个没有评论).

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).

有没有办法规范化"我的所有网址,使其不带斜杠?我已经尝试添加strict routing 标志来表达但结果是一样的

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

谢谢

推荐答案

尝试为此添加一个中间件;

Try adding a middleware for that;

app.use((req, res, next) => {
  const test = /?[^]*//.test(req.url);
  if (req.url.substr(-1) === '/' && req.url.length > 1 && !test)
    res.redirect(301, req.url.slice(0, -1));
  else
    next();
});

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

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