정적 파일
Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 20개 중 9번째.
스타일시트나 이미지는 변경되지 않으며, 파일마다 경로를 만드는 것은 불필요한 작업입니다.
app.use(express.static('assets'));express.static('assets')는 assets 폴더의 파일을 파일 이름 그대로 제공합니다. assets/logo.png는 GET /logo.png 요청에 응답합니다. 폴더 이름은 URL에 포함되지 않습니다. Express는 확장자를 기준으로 콘텐츠 유형을 선택합니다. .css는 text/css, .png는 image/png입니다. 파일이 없는 경로는 다음 라우트로 넘어갑니다.
app.use는 모든 요청에 대해 실행되는 함수를 추가합니다. 다음 장에서는 이러한 함수에 대해 알아봅니다. 이제 프로젝트에 스타일시트가 들어 있는 public 폴더가 있습니다.
챌린지
쉬움public폴더를 제공하여GET /style.css요청에 파일이 응답하도록 하세요.- 홈 페이지에서
<link rel="stylesheet" href="/style.css">를 사용해 연결하세요.
페이지 보기에서 /를 연 다음 GET /style.css와 GET /missing.css를 보내세요.
직접 해보기
import express from 'express';
import { recipes } from './data.js';
const app = express();
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(`<h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// 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');
});