استجابات JSON
جزء من قسم أساسيات Express في رحلة Node.js على Coddy. الدرس 6 من 20.
يحتاج البرنامج الذي يستدعي خادمك إلى بيانات يمكنه قراءتها، لا إلى جملة.
app.get('/api/weather', (req, res) => {
res.json({ city: 'Oslo', temp: 4, rain: true });
});JSON هو تنسيق نصي للكائنات والمصفوفات. يحوّل res.json(value) القيمة إلى JSON ويضبط ترويسة Content-Type على application/json؛ والترويسة سطر ذو اسم يُرسَل مع الاستجابة، وتوضح هذه الترويسة نوع المحتوى الذي يليها. يتلقى العميل {"city":"Oslo","temp":4,"rain":true} ويقرأ temp بوصفه عددًا.
إرسال res.send لسلسلة نصية يرسل text/html، ما يضطر البرنامج إلى تحليلها. تبدأ المسارات المخصصة للبرامج عادةً بـ /api، وبذلك لا تتشارك الصفحات والبيانات المسار نفسه أبدًا.
التحدي
سهل- يعيد
GET /api/recipesمصفوفةrecipesبصيغة JSON. - يعيد
GET /api/recipes/:idوصفة واحدة بصيغة JSON؛ ويؤدي المعرّف غير المعروف إلى استجابة404.
أرسل GET /api/recipes وGET /api/recipes/2 وGET /api/recipes/99. قارن الترويسات مع GET /recipes.
جرّب بنفسك
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('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.