קודי סטטוס
חלק מהיחידה יסודות 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: אירעה תקלה בשרת.
אתגר
קלמזהה לא מוכר ב־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');
});