Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express adds slash at the end of url weirdly

I'm using Node.js and Express framework for developing a website. I faced weird misbehaviour with a url. When i click to related link url, url becomes "localhost:3000/images/" - a slash is added at the end as you can see. But when i change all 'images' to 'img' or else url becomes "localhost:3000/img" no slash added. Why router behaves like that? Codes written below. (I'm using Jade template Engine)

//bar.jade    
li.nav-item
      a.nav-link(href='images')
        i.icon-camera
        |  Images

//end of bar.jade


//images.js (router)
var express = require('express');
var router = express.Router();

/* GET home page. */

router.get('/', function(req, res, next) {
  res.render('images', { title: 'Express'});
});

module.exports = router;
//end of router .js



//app.js
var images =require('./routes/images');
........
........
app.use('/images',images);
//end of app.js
like image 683
Emre Avatar asked Dec 06 '22 19:12

Emre


2 Answers

I think I know what's going on: you're also using the express.static() middleware, and in your public directory you have a directory called images/.

This middleware will generate redirects ending with a slash when you try to request a URL that matches a public directory (even when that directory is empty or matches another route).

To disable this behaviour, set the redirect option to false.

like image 193
robertklep Avatar answered Dec 30 '22 14:12

robertklep


By default in express router “/foo” and “/foo/” are treated the same by the router. You can disable this behavior with strict: true option.

Express.Router documentation

var router = express.Router({strict: true});
like image 31
Alexey B. Avatar answered Dec 30 '22 12:12

Alexey B.