Menu
CoddyTech

Durum Kodları

Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 7 / 23.

Program, gövdeden önce durum kodunu okur; bu nedenle 200 koduyla gönderilen bir hata başarılı 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; bu nedenle .json(...) aynı satırda ardından gelebilir. return, hata oluştuktan 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: istekte eksik alan gibi bir hata var.
  • 404: bu yolda veya kimlikte hiçbir şey yok.
  • 500: sunucuda hata oluştu.
challenge icon

Görev

Kolay

API'yi okuyan bir program önce durum kodunu, sonra gövdeyi kontrol eder. Bulunamama durumunu her ikisi için de açık hâle getir.

  1. server.js dosyasında, /api/recipes/:id rotasında, id'si eşleşen bir tarif olmadığında gerçekleşen şeyi değiştir. Durum kodu 404 olarak kalsın, ancak metin yerine şu JSON'u gönder: {"error": "No such recipe"}
  2. abc gibi sayı olmayan bir id de hiçbir tarifle eşleşmez. Aynı 404 durum kodunu ve aynı JSON'u alır.

Dene: “Çalıştır”a bas ve /api/recipes/99 gönder. 404 durum kodunu ve {"error":"No such recipe"} değerini görmelisin. /api/recipes/abc gönder: yine aynı 404 durum kodu ve JSON. /api/recipes/3 gönder: 200 durum kodu 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