Menu
CoddyTech

HTML 페이지

Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 20개 중 8번째.

레시피는 실제 페이지에 있어야 하며, 브라우저는 HTML만 렌더링합니다. 페이지는 HTML 문자열입니다. res.send는 이를 text/html로 보내고, 템플릿 문자열은 데이터로 채웁니다.

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

URL의 일부나 누군가 입력한 제목처럼 외부에서 온 텍스트에는 < 또는 &가 포함될 수 있습니다. 이를 있는 그대로 HTML에 넣으면 <script>는 방문자의 브라우저에서 실행되는 코드가 됩니다. escapeHtml은 이러한 문자를 브라우저가 텍스트로 표시하는 엔티티로 바꿉니다. &를 먼저 바꾸므로 &lt;의 &는 다시 바뀌지 않습니다.

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

챌린지

쉬움
  • GET /는 모든 레시피 제목을 나열하는 HTML 페이지를 응답합니다.
  • 각 제목은 <a href="/recipes/2">와 같이 해당 페이지로 연결됩니다.
  • 모든 제목은 escapeHtml을 거칩니다.

페이지 보기에서 /를 열고 Fish & Chips를 클릭하세요.

직접 해보기

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

const app = express();

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

// type('text')는 일반 텍스트를 전송하므로 각 제목이 별도의 줄에 표시됩니다.
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 icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Express 기초의 모든 레슨