Junior #express#middleware
Middleware trong Express là gì?
⚡ Trả lời nhanh
Middleware là hàm (req, res, next) chạy tuần tự trước handler cuối: dùng cho log, auth, parse body, xử lý lỗi. Gọi next() để chuyển tiếp, hoặc kết thúc response.
app.use(express.json()); // parse body
const auth = (req, res, next) => {
if (!req.headers.authorization) return res.status(401).end();
next(); // cho đi tiếp
};
app.get('/me', auth, (req, res) => res.json({ ok: true }));
// Error middleware: đủ 4 tham số, đặt cuối cùng
app.use((err, req, res, next) => res.status(500).json({ message: err.message }));