İlk Middleware'iniz
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 11 / 20.
Günlüğe bir satır yazmak gibi bazı işler her istekte yapılır ve bunları her rotaya eklemek hiç bitmez.
let visits = 0;
app.use((req, res, next) => {
visits++;
next();
});app.use işlevine verilen bir işlev ara yazılımdır: Express bunu eklenme sırasına göre, altındaki rotalardan önce her istek için çalıştırır. Bu işlev üçüncü bir bağımsız değişken olan next'i alır. next() çağrısı, isteği sıradaki öğeye aktarır. Ne yanıt veren ne de next() çağıran bir ara yazılım, isteğin sonsuza kadar beklemesine neden olur.
Son bölümdeki express.static de bir ara yazılımdır: Bir dosya bulduğunda yanıt verir, bulamadığında ise next() çağrısı yapar.
Görev
KolayHer isteğin yöntemini ve yolunu GET /recipes/2 gibi yazdıran bir ara katman ekle.
GET /recipes/2 ve GET /nope isteklerini gönder, ardından Konsol'u oku.
Kendin dene
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.use(express.static('public'));
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// type('text') düz metin gönderir, bu nedenle her başlık ayrı bir satırda görünür.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.get('/menu', (req, res) => {
res.redirect(301, '/recipes');
});
app.get('/menu/:id', (req, res) => {
res.redirect(301, `/recipes/${req.params.id}`);
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Express Temelleri bölümündeki tüm dersler
3Middleware
İlk Middleware'iniz