Create a simple Express server
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});Example of logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});Protect routes with JWT verification
const jwt = require('jsonwebtoken');
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access denied');
try {
const verified = jwt.verify(token, process.env.JWT_SECRET);
req.user = verified;
next();
} catch (err) {
res.status(400).send('Invalid token');
}
}
app.get('/protected', authMiddleware, (req, res) => {
res.send('This is a protected route');
});