Redirect all trailing slashes globally in express

后端 未结 7 1639
醉话见心
醉话见心 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:35

    I'm adding this answer because I had too many issues with other solutions.

    /**
     * @param {express.Request} req
     * @param {express.Response} res
     * @param {express.NextFunction} next
     * @return {void}
     */
    function checkTrailingSlash(req, res, next) {
      const trailingSlashUrl = req.baseUrl + req.url;
      if (req.originalUrl !== trailingSlashUrl) {
        res.redirect(301, trailingSlashUrl);
      } else {
        next();
      }
    }
    
    router.use(checkTrailingSlash);
    

    This will translate:

    /page ==> /page/
    /page?query=value ==> /page/?query=value
    
    0 讨论(0)
提交回复
热议问题