I am building a Node.js server using Express, and I have defined a couple of routes like this:
const express = require('express');
const app = express();
app.get('/api', (req, res) => {
res.send('API Route');
});
app.get('/home', (req, res) => {
res.send('Home Route');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
When I run the server and access http://localhost:3000/home or http://localhost:3000/api in my browser, I get the expected responses. However, if I try to access http://localhost:3000/home/ (with a trailing slash), it returns a 404 error. Why does this happen, and how can I make my routes handle trailing slashes correctly?
I tried adding more routes explicitly with trailing slashes, like this:
app.get('/home/', (req, res) => {
res.send('Home Route');
});
This works, but I was expecting Express to handle trailing slashes automatically. I don’t want to duplicate routes. How can I handle this efficiently?
The issue is that Express treats routes with and without trailing slashes as different routes. If you want your routes to handle both cases (with and without trailing slashes), you can use middleware like app.use() to normalize your routes.
Here’s an example of how you can handle this globally:
app.use((req, res, next) => {
if (req.path.endsWith('/') && req.path.length > 1) {
const newPath = req.path.slice(0, -1);
res.redirect(301, newPath);
} else {
next();
}
});
This will redirect any route with a trailing slash to the same route without the trailing slash. For example, /home/ will be redirected to /home.
Alternatively, you can use the strict option in Express to ignore trailing slashes globally:
const app = express();
app.set('strict routing', false);