Start learning free

LESSON 56 OF 161 · FRONTEND: TALKING TO AN API

Send Data: POST in JavaScript

Practice

So far the page only asked: every fetch was a GET, which reads. To change something on the server, the page sends a POST with data in its body. The body is text: JSON.stringify turns an object into JSON text, and a Content-Type: application/json header tells the server to read it as JSON.

All of that goes in a second argument to fetch, the options object. For example, an order form could send:

const response = await fetch("/api/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "ana@example.com" }),
});

Without a method, fetch sends a GET. Without the header, the server doesn't read the body, even when the body looks right. The cart now lives on the server: the 201 answer to POST /api/cart holds the whole cart, items and total, so the page draws its cart from the answer instead of changing its own array.

The check clicks "Add to cart" on the Mug twice, then on the Teapot. Your page must show:

> click "Add to cart" in "Mug"
  request: POST /api/cart {"product_id": 1, "quantity": 1} -> 201
  + item: Mug x 1 $12
  + text: Total: $12
> click "Add to cart" in "Mug"
  request: POST /api/cart {"product_id": 1, "quantity": 1} -> 201
  + item: Mug x 2 $24
  + text: Total: $24
> click "Add to cart" in "Teapot"
  request: POST /api/cart {"product_id": 6, "quantity": 1} -> 201
  + item: Teapot x 1 $22
  + text: Total: $46

Your task: write addToCart(id) as an async function that sends POST /api/cart with the JSON header and the body { product_id: id, quantity: 1 }, then puts the answer's items into cart and calls render.


Assignment
Follow the Coding Tutorial to write addToCart, the shop page's first request that sends data, and draw the cart from the server's answer.


Hint
The options object has three entries: method, headers and body. If the check prints a 404 for the Mug, look for the missing Content-Type header.


STEP 1 OF 8
    Ctrl + Enter to check

    Fetch Post Json in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free