Menu
CoddyTech

HTML Sayfaları

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

Tariflerin gerçek bir sayfada yer almalı ve tarayıcı yalnızca HTML çizer. Bir sayfa, HTML dizgesidir: res.send bunu text/html olarak gönderir ve şablon dizgesi onu verilerle doldurur.

app.get('/weather/:city', (req, res) => {
    const city = escapeHtml(req.params.city);
    res.send(`<h1>Weather in ${city}</h1><p>Sunny</p>`);
});

URL'nin bir bölümü veya birinin yazdığı bir başlık gibi dışarıdan gelen metin, < ya da & içerebilir. HTML'ye olduğu gibi eklenirse <script>, ziyaretçinizin tarayıcısında çalışan bir koda dönüşür. escapeHtml, bu karakterleri tarayıcının metin olarak gösterdiği varlıklara dönüştürür. Önce & karakterini değiştirdiğinden, &lt; içindeki & yeniden değiştirilmez.

const escapeHtml = (text) =>
    text
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');
challenge icon

Görev

Kolay
  • GET / bir HTML sayfası döndürür ve bu sayfada tüm tarif başlıkları listelenir.
  • Her başlık, <a href="/recipes/2"> gibi kendi sayfasına bağlantı verir.
  • Her başlık escapeHtml işlevinden geçirilir.

Sayfa görünümünde / yolunu aç ve Fish & Chips öğesine tıkla.

Kendin dene

import express from 'express';
import { recipes } from './data.js';

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// 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');
});
quiz iconKendini test et

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