Menu
CoddyTech

404 İşleyicisi

Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 16 / 23.

Express, bilinmeyen bir yolu kendi sayfasıyla yanıtlar: Cannot GET /x; bu sayfa ne sitenize ne de API'nize uyar.

app.use((req, res) => {
    res.status(404).send('No forecast here. Try /weather/oslo');
});

Yolu belirtilmemiş bir ara yazılım, kendisine ulaşan her istek için çalışır. Bunu tüm rotalardan ve express.static çağrısından sonra ekleyin: yanıtlanan istekler buraya hiç ulaşmaz, dolayısıyla yalnızca hiçbir şeyin yanıtlamadığı istekleri görür. Yanıt verdiği için next kullanması gerekmez.

req.path, sorgu dizesi olmadan yolu verir; bu nedenle req.path.startsWith('/api/') bir API çağrısını sayfa isteğinden ayırt etmenizi sağlar.

challenge icon

Görev

Kolay

Var olmayan yollar, Express'in düz Cannot GET sayfasını gösterir. Bunu kendi yanıtlarınızla değiştirin: API için JSON, ziyaretçiler içinse anlaşılır bir sayfa sunun.

  1. server.js dosyasında, tüm rotalardan ve express.static satırından sonra, yol belirtmeden son bir app.use ekleyin. Bir isteğe daha önce yanıt verildiyse bu noktaya ulaşmaz; dolayısıyla bu ara yazılım yalnızca başka hiçbir şeyin işlemediği istekleri görür.
  2. Yol /api/ ile başlıyorsa, durum kodu 404 olan şu JSON yanıtını döndürün: {"error": "Not found"}
  3. Diğer tüm yollar için, durum kodu 404 olan ve Page not found sözlerini içeren bir HTML sayfası döndürün; örneğin <h1>Page not found</h1>. Ana sayfaya dönen bir bağlantı da hoş bir ayrıntı olur.

Deneyin: “Çalıştır” düğmesine basın ve /api/nope isteğini gönderin. 404 durum kodunu ve {"error":"Not found"} yanıtını görmelisiniz. /nope isteğini gönderin: 404 durum kodu ve Page not found yazan bir sayfa görmelisiniz. /api/recipes/1 isteğini gönderin: 200 durum kodu ve Tomato Soup yanıtını görmelisiniz; bu da rotalarınızın hâlâ önce çalıştığını gösterir.

Kendin dene

import { escapeHtml } from './html.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.use((req, res, next) => {
    res.set('X-Request-Id', randomUUID());
    next();
});

app.use(express.json());

app.use(express.static('public'));

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, böylece 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.post('/api/recipes', (req, res) => {
    const { title, tags } = req.body;
    if (!title) {
        res.status(400).json({ error: 'A recipe needs a title' });
        return;
    }
    const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
    recipes.push(recipe);
    res.status(201).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');
});

Express Temelleri bölümündeki tüm dersler

Kendi başına pratik yap: Express playground