Redirect all trailing slashes globally in express

后端 未结 7 1672
醉话见心
醉话见心 2020-11-28 23:40

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

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

    r         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 00:15

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

提交回复
热议问题