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
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
.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With