رموز الحالة
جزء من قسم أساسيات Express في رحلة Node.js على Coddy. الدرس 7 من 23.
يقرأ البرنامج رمز الحالة قبل المتن، لذلك يبدو الخطأ المُرسَل مع الرمز 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: حدث عطل في الخادم.
التحدي
سهليقرأ البرنامج الذي يقرأ واجهة API الخاصة بك رمز الحالة أولًا، ثم متن الاستجابة. اجعل حالة عدم العثور واضحة لكليهما.
- في
server.js، في المسار/api/recipes/:id، غيّر ما يحدث عندما لا توجد وصفة لها هذا المعرّف. أبقِ الحالة 404، لكن أرسل JSON هذا بدلًا من النص:{"error": "No such recipe"} - المعرّف غير الرقمي، مثل
abc، لا يطابق أي وصفة أيضًا. وستكون له حالة 404 نفسها وJSON نفسه.
جرّب ذلك: اضغط «العب» وأرسل /api/recipes/99. ينبغي أن ترى الحالة 404 و{"error":"No such recipe"}. أرسل /api/recipes/abc: ستحصل على الحالة 404 نفسها وJSON نفسه. أرسل /api/recipes/3: الحالة 200 ووصفة Lentil Curry.
جرّب بنفسك
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
تدرّب بنفسك: Playground لـ Express