Middleware
מהו Middleware?
Middleware הן פונקציות שרצות בין קבלת הבקשה לשליחת התשובה.
[בקשה] → [Middleware 1] → [Middleware 2] → [Route] → [תשובה]
מבנה בסיסי
const myMiddleware = (req, res, next) => {
// עשה משהו
console.log('בקשה:', req.method, req.path);
// המשך הלאה
next();
};
app.use(myMiddleware);
סוגי Middleware
1. Application-level
// Runs on all requests
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
// רץ רק על נתיב מסוים
app.use('/api', (req, res, next) => {
console.log('API request');
next();
});
2. Built-in Middleware
// Parse JSON
app.use(express.json());
// Parse URL-encoded
app.use(express.urlencoded({ extended: true }));
// קבצים סטטיים
app.use(express.static('public'));
3. Third-party Middleware
import cors from 'cors';
import morgan from 'morgan';
app.use(cors()); // אפשור CORS
app.use(morgan('dev')); // לוגים
סדר ביצוע
app.use((req, res, next) => {
console.log('1. ראשון');
next();
});
app.use((req, res, next) => {
console.log('2. שני');
next();
});
app.get('/', (req, res) => {
console.log('3. Route');
res.send('סיום');
});
// Output: 1, 2, 3
Middleware לאימות
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'לא מורשה' });
}
// אימות הטוקן...
next();
};
// שימוש על routes ספציפיים
app.get('/protected', authMiddleware, (req, res) => {
res.json({ secret: 'data' });
});
Error Handling Middleware
// Must be at the end!
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'שגיאה בשרת' });
});
בדקו את עצמכם
נסו לענות לבד לפני שאתם פותחים את התשובה.
-
מה יקרה ב-Middleware ששוכח לקרוא ל-next() ולא שולח תשובה?
הצגת התשובה
תשובה א. Middleware חייב לסיים את הבקשה או להעביר אותה הלאה.
-
למה הסדר של
app.useחשוב?הצגת התשובה
תשובה א. Route שרץ לפני express.json() יקבל req.body undefined.