Menu
CoddyTech

A Page That Calls the API

Part of the REST APIs section of Coddy's Node.js journey. Lesson 14 of 18.

Your API has no screen yet. A page served by the same server can call it with fetch, with no CORS needed, since the origin is the same. express.static('public') serves public/index.html at /.

const res = await fetch('/api/comments/3', { method: 'DELETE' });
if (!res.ok) {
    const { error } = await res.json();
    message.textContent = error.message;
}

res.ok is true for any status from 200 to 299. A body goes in the body option, and JSON needs two things: the text from JSON.stringify(...) and the header 'Content-Type': 'application/json', which express.json() looks for. A FormData body sends form fields instead, and this API refuses those. The checks cannot run a page's JavaScript: they check the page is served, that it sends JSON, and the API calls it makes.

challenge icon

Challenge

Easy
  • Serve the public folder with express.static, so / opens public/index.html.
  • The form's submit sends { "title" } to POST /api/tasks as JSON. On success, clear the form and load(); on an error, show error.message in #message.

Open / in the page view, add a task, then add the same title again.

Try it yourself

<!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>

All lessons in REST APIs