API'yi Çağıran Bir Sayfa
Coddy'nin Node.js Journey'sinin REST API'leri bölümünün bir parçası. Ders 14 / 18.
API'nizin henüz bir ekranı yok. Aynı sunucunun sunduğu bir sayfa, kaynak aynı olduğundan CORS gerekmeden fetch ile API'yi çağırabilir. express.static('public'), public/index.html dosyasını / adresinde sunar.
const res = await fetch('/api/comments/3', { method: 'DELETE' });
if (!res.ok) {
const { error } = await res.json();
message.textContent = error.message;
}res.ok, 200 ile 299 arasındaki tüm durum kodları için true değerini alır. İstek gövdesi body seçeneğine konur ve JSON için iki şey gerekir: JSON.stringify(...) ile elde edilen metin ve express.json() tarafından aranan 'Content-Type': 'application/json' başlığı. FormData gövdesi bunun yerine form alanlarını gönderir ve bu API bunları reddeder. Denetimler bir sayfanın JavaScript kodunu çalıştıramaz: sayfanın sunulduğunu, JSON gönderdiğini ve yaptığı API çağrılarını denetler.
Görev
Kolaypublicklasörünüexpress.staticile sun; böylece/,public/index.htmldosyasını açar.- Formun gönderilmesi, JSON olarak
{ "title" }verisiniPOST /api/tasksadresine gönderir. Başarılı olursa formu temizle veload()işlevini çağır; hata olursaerror.messagedeğerini#messageiçinde göster.
Sayfa görünümünde / adresini aç, bir görev ekle, ardından aynı başlığı tekrar ekle.
Kendin dene
<!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>