Menu
CoddyTech

Durum Kodları

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

Bir program, gövdeden önce durum kodunu okur; bu nedenle 200 koduyla 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: istek hatalı; örneğin bir alan eksik.
  • 404: bu yolda veya kimlikte hiçbir şey yok.
  • 500: sunucuda hata oluştu.
challenge icon

Görev

Kolay

GET /api/recipes/:id adresinde bilinmeyen bir id, { "error": "No such recipe" } ile 404 yanıtı verir.

GET /api/recipes/99 ve GET /api/recipes/abc isteklerini gönderin, ardından GET /api/recipes/3 isteğini gönderin ve durum kodlarını karşılaştırın.

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, bu nedenle 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