Menu
CoddyTech

Yönlendirmeler

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

Sayfalar taşınır ve yer işaretlerindeki ya da arama sonuçlarındaki eski bağlantılar yine de bir yere yönlendirmelidir.

app.get('/old-prices', (req, res) => {
    res.redirect(301, '/prices');
});

Yönlendirme, yeni URL'yi belirten bir durum kodu ve Location başlığıyla yanıt verir; tarayıcı da hemen bu URL'yi ister. res.redirect ikisini de ayarlar.

Durum kodu, taşınmanın ne kadar süreceğini belirtir. 301, kalıcı olarak taşındığı anlamına gelir: tarayıcılar ve arama motorları yeni adresi hatırlar ve eski adresi istemeyi bırakır. Durum kodu belirtmediğinizde varsayılan olan 302 ise şimdilik anlamına gelir; bu yüzden eski URL'yi kullanmaya devam ederler.

challenge icon

Görev

Kolay
  • GET /menu kalıcı olarak /recipes konumuna taşındı.
  • GET /menu/:id, aynı id ile /recipes/:id konumuna taşındı.

GET /menu/3 isteğini gönder ve durum kodunu ve Location başlığını oku. GET /menu/42 isteğini de gönder.

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('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');

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.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

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