Statik Dosyalar
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 9 / 20.
Bir stil sayfası veya görsel hiç değişmez ve her dosya için bir rota oluşturmak gereksiz iştir.
app.use(express.static('assets'));express.static('assets'), assets klasöründeki dosyaları kendi adlarıyla sunar: assets/logo.png, GET /logo.png isteğini yanıtlar. Klasör adı URL'nin bir parçası değildir. Express, içerik türünü uzantıdan belirler: .css için text/css, .png için image/png. Dosyası olmayan bir yol, rotalarınıza ilerler.
app.use, her istek için çalışan bir işlev ekler; sonraki bölüm bu işlevlerle ilgili. Projenizde artık stil sayfası içeren bir public klasörü var.
Görev
Kolaypublicklasörünü sun, böyleceGET /style.cssdosyayı yanıt olarak döndürür.- Ana sayfadan
<link rel="stylesheet" href="/style.css">ile bağlantı ver.
Sayfa görünümünde / adresini aç, ardından GET /style.css ve GET /missing.css isteklerini gönder.
Kendin dene
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') 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');
});