Sorgu Dizeleri
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 5 / 20.
Bir liste sayfasında genellikle hangi tariflerin gösterileceği gibi seçenekler gerekir; her seçenek için yeni bir rota oluşturmak ise çok fazla rota anlamına gelir.
app.get('/books', (req, res) => {
const { author } = req.query;
res.send(author ? 'Books by ' + author : 'All books');
});Sorgu dizesi, URL'nin ? işaretinden sonraki bölümüdür ve Express bunu req.query içine koyar. GET /books?author=Austen ifadesi req.query.author === 'Austen' sonucunu verir. ? yoksa değer undefined olur. Birden fazla seçenek & ile birleştirilir: /books?author=Austen&year=1813.
Bir rota parametresi yolun bir parçasıdır ve tek bir şeyi belirtir. Bir sorgu seçeneği listeyi filtreler veya sıralar ve atlanabilir.
Görev
KolayGET /recipes?tag=vegan, bu etikete sahip tariflerin yalnızca başlıklarını, her satırda bir tane olacak şekilde listeler.tagolmadan tüm başlıkları listeler.
GET /recipes?tag=vegan, GET /recipes?tag=dessert ve GET /recipes isteklerini gönder.
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'));
});
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('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});