Daha Fazla Rota
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 3 / 23.
Bir sitede birden fazla sayfa vardır, bu nedenle sunucunun her yol için bir rotaya ihtiyacı vardır.
app.get('/books', (req, res) => {
res.send('12 books on the shelf');
});
app.get('/opening-hours', (req, res) => {
res.send('Monday to Friday, 10 to 6');
});Express her isteğin yolunu okur ve o yola ait rotayı çağırır: GET /books ilk işleve, GET /opening-hours ise ikinci işleve ulaşır. Rotası olmayan bir yol için Express'in kendi 404 sayfası gösterilir. Bir rotanın yolu her zaman / ile başlar.
Recipe Box geri döndü; içinde dört tarif bulunan bir data.js dosyası ve bu tariflerin başlıklarını listeleyen bir /recipes rotası var.
Görev
KolayRecipe Box'ın ana sayfanın ve tarif listesinin yanında bir Hakkında sayfasına da ihtiyacı var.
server.jsdosyasında, yorumun// Add the /about page here.dediği yere/aboutyolu için bir rota ekle. Bu cümleyi, sonundaki nokta da dâhil olmak üzere gönderir:Recipe Box collects family recipes./ve/recipesrotalarını olduğu gibi bırak.
Dene: Çalıştır'a bas ve /about isteğini gönder. Recipe Box collects family recipes. yanıtını görmelisin. /recipes isteğini gönder: dört tarif başlığı, her satırda bir tane. Ardından /about-us isteğini gönder. Hiçbir rotanın bu yolu yoktur, bu nedenle Express 404 durum koduyla ve Cannot GET /about-us yanıtını verir. İstek çubuğundaki yol listesi, uygulamanın sahip olduğu rotaları gösterir.
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) => {
res.type('text').send(recipes.map((recipe) => recipe.title).join('\n'));
});
// /about sayfasını buraya ekleyin.
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
Express Temelleri bölümündeki tüm dersler
Kendi başına pratik yap: Express playground