I'm learning Express.js and I'm a bit confused about the difference between middleware functions and route handlers. I understand that middleware functions usually have the next argument, but I'm not clear on when a function is considered middleware and when it is a route handler.
Are Route Handlers Considered Middleware in Node.js Express?
Questions:
- Does the following code have middlewares? And which are the middlewares in this code?
- Are the functions like app.get('/', ...), app.post('/verify', ...), app.get('/home', ...), and app.get('/logout', ...) considered middlewares?
- Do middleware functions always need to have the next argument?
- Can you explain the role of middleware versus route handlers in Express.js?
const express = require('express');
const app = express();
const hbs = require('hbs');
const nocache = require('nocache');
const session = require('express-session');
app.use(express.static('public'));
app.set('view engine', 'hbs');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
}));
app.use(nocache());
const username = 'admin';
const password = 'admin@123';
app.get('/', (req, res) => {
if (req.session.user) {
res.render('home');
} else {
if (req.session.passwordwrong) {
res.render('login', { msg: "invalid credentials" });
req.session.passwordwrong = false;
} else {
res.render('login');
}
}
});
app.post('/verify', (req, res) => {
if (req.body.username === username && req.body.password === password) {
req.session.user = req.body.username;
res.redirect('/home');
} else {
req.session.passwordwrong = true;
res.redirect('/');
}
});
app.get('/home', (req, res) => {
if (req.session.user) {
res.render('home', { username: username });
} else {
if (req.session.passwordwrong) {
req.session.passwordwrong = false;
res.render('login', { msg: "invalid credentials" });
} else {
res.render('login');
}
}
});
app.get('/logout', (req, res) => {
req.session.destroy();
res.render('login', { msg: 'logged out' });
});`your text`
app.listen(3000, () => console.log('server running on port 3000'));