Daha Fazla Rota
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 3 / 23.
Bir sitenin birden fazla sayfası 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 bu yola karşılık gelen rotayı çağırır: GET /books ilk işleve, GET /opening-hours ise ikinci işleve ulaşır. Rotası olmayan bir yol, Express'in kendi 404 sayfasını gösterir. Bir rotanın yolu her zaman / ile başlar.
Recipe Box yeniden karşınızda; 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 ihtiyacı var.
server.jsdosyasında, yorumun// Add the /about page here.dediği yere/aboutyolu için bir rota ekle. Şu cümleyi, nokta dahil, gönderir:Recipe Box collects family recipes./ve/recipesrotalarını olduğu gibi bırak.
Dene: “Çalıştır” düğmesine bas ve /about yoluna istek gönder. Recipe Box collects family recipes. metnini görmelisin. /recipes yoluna istek gönder: dört tarif başlığı, her satırda bir tane. Ardından /about-us yoluna istek gönder. Bu yola karşılık gelen bir rota yok, bu nedenle Express 404 durumuyla ve Cannot GET /about-us mesajıyla yanıt verir. İstek çubuğundaki yollar 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