דף שקורא ל־API
חלק מהיחידה REST APIs במסלול ה-Node.js של Coddy. שיעור 14 מתוך 18.
ל־API שלך עדיין אין ממשק. דף שמוגש מאותו שרת יכול לקרוא לו באמצעות fetch, ללא צורך ב־CORS, מכיוון שהמקור זהה. express.static('public') מגיש את public/index.html בכתובת /.
const res = await fetch('/api/comments/3', { method: 'DELETE' });
if (!res.ok) {
const { error } = await res.json();
message.textContent = error.message;
}res.ok הוא true עבור כל סטטוס מ־200 עד 299. גוף הבקשה נשלח באפשרות body, ול־JSON דרושים שני דברים: הטקסט שמתקבל מ־JSON.stringify(...) והכותרת 'Content-Type': 'application/json', שאותה express.json() מחפשת. גוף מסוג FormData שולח שדות טופס במקום זאת, וה־API הזה דוחה אותם. הבדיקות אינן יכולות להריץ את JavaScript של הדף: הן בודקות שהדף מוגש, שהוא שולח JSON ושהוא מבצע את קריאות ה־API.
אתגר
קל- הגישו את התיקייה
publicבאמצעותexpress.static, כך ש־/יפתח אתpublic/index.html. - שליחת הטופס שולחת את
{ "title" }אלPOST /api/tasksכ־JSON. במקרה של הצלחה, נקו את הטופס והפעילו אתload(); במקרה של שגיאה, הציגו אתerror.messageבתוך#message.
פתחו את / בתצוגת הדף, הוסיפו משימה ואז הוסיפו שוב את אותו הכותרת.
נסו בעצמכם
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tasks</title>
</head>
<body>
<h1>Tasks</h1>
<ul id="list"></ul>
<form id="add">
<input name="title" placeholder="New task" required>
<button>Add</button>
</form>
<p id="message"></p>
<script>
const list = document.querySelector('#list');
const form = document.querySelector('#add');
const message = document.querySelector('#message');
async function load() {
const res = await fetch('/api/tasks?limit=50');
const page = await res.json();
list.replaceChildren(...page.items.map((task) => {
const item = document.createElement('li');
item.textContent = (task.done ? '[x] ' : '[ ] ') + task.title;
return item;
}));
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Send the title to POST /api/tasks as JSON. On success clear
// the form and load() again; on an error show its message.
});
load();
</script>
</body>
</html>