Menu
CoddyTech

رموز الحالة

جزء من قسم أساسيات Express في رحلة Node.js على Coddy. الدرس 7 من 20.

يقرأ البرنامج رمز الحالة قبل المتن، لذا يبدو الخطأ المُرسل مع الرمز 200 كأنه نجاح.

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) الحالة وتُعيد res، لذا يمكن أن يأتي بعدها .json(...) في السطر نفسه. توقف return الدالة بعد الخطأ. أكثر الرموز التي ستصادفها:

  • 200: نجح الطلب (وهذه هي القيمة الافتراضية).
  • 201: تم إنشاء شيء ما.
  • 400: الطلب غير صحيح، مثلًا عند غياب أحد الحقول.
  • 404: لا يوجد شيء في هذا المسار أو بهذا المعرّف.
  • 500: حدث إخفاق في الخادم.
challenge icon

التحدي

سهل

يُرجع المعرّف غير المعروف في GET /api/recipes/:id استجابة 404 مع { "error": "No such recipe" }.

أرسل GET /api/recipes/99 وGET /api/recipes/abc، ثم GET /api/recipes/3، وقارن بين حالات الاستجابة.

جرّب بنفسك

import express from 'express';
import { recipes } from './data.js';

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// ترسل type('text') نصًا عاديًا، لذا يظهر كل عنوان في سطر مستقل.
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