Durum Kodları
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 7 / 23.
Program, yanıt gövdesinden önce durum kodunu okur; bu yüzden 200 ile gönderilen bir hata başarılıymış gibi görünür.
app.get('/api/loans', (req, res) => {
if (!req.query.member) {
res.status(400).json({ error: 'Say which member' });
return;
}
res.json(loansOf(req.query.member));
});res.status(code) durumu ayarlar ve res döndürür; böylece .json(...) aynı satırda devam edebilir. return, hatadan sonra işlevi durdurur. En sık karşılaşacağın kodlar:
- 200: işlem başarılı (varsayılan).
- 201: bir şey oluşturuldu.
- 400: eksik alan gibi bir nedenle istek hatalı.
- 404: bu yolda veya kimlikte hiçbir şey yok.
- 500: sunucuda bir hata oluştu.
Görev
KolayAPI'nizi okuyan bir program önce durum kodunu, ardından gövdeyi kontrol eder. Bulunamayan durumunu her ikisi için de açık hâle getirin.
server.jsdosyasında,/api/recipes/:idrotasında, kimliğe sahip bir tarif bulunmadığında ne olduğunu değiştirin. Durumu 404 olarak bırakın, ancak metin yerine şu JSON'u gönderin:{"error": "No such recipe"}abcgibi sayı olmayan bir kimlik de hiçbir tarifle eşleşmez. Aynı 404 durumunu ve aynı JSON'u alır.
Deneyin: “Oyna” düğmesine basın ve /api/recipes/99 isteğini gönderin. 404 durumunu ve {"error":"No such recipe"} yanıtını görmelisiniz. /api/recipes/abc isteğini gönderin: aynı 404 durumu ve JSON. /api/recipes/3 isteğini gönderin: 200 durumu ve Lentil Curry tarifi.
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) => {
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).send('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');
});
Express Temelleri bölümündeki tüm dersler
Kendi başına pratik yap: Express playground