Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C4 · Lekcja 4
ZadaniePOST { name: 'Anna' } to /api/users with proper Content-Type. Parse the returned JSON, log the created user's id (should be 42).

POSTing JSON: metoda + nagłówki + treść

100 XP8 min
Teoria

The four-field POST

const r = await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Anna", age: 30 }),
});

Four fields cover 90% of API calls:

  • method — "GET" (default), "POST", "PUT", "PATCH", "DELETE".
  • headers — Content-Type tells the server how to parse the body; Authorization carries the token.
  • body — what to send. For JSON: JSON.stringify(obj). For form data: a FormData instance.

The two body shapes you'll write

// JSON body (most modern APIs)
body: JSON.stringify({ name: "Anna" }),
headers: { "Content-Type": "application/json" },

// Form-urlencoded body (legacy APIs, OAuth)
body: new URLSearchParams({ name: "Anna" }),
// no Content-Type needed — fetch sets application/x-www-form-urlencoded

FormData works the same way — fetch detects it and sets the multipart content-type automatically (don't set it manually, you'll mangle the boundary).

Reading the response

const created = await r.json();   // { id: 42, name: "Anna" } if the API returns the created record
console.log(created.id);

Most REST APIs return the created resource on POST so the client doesn't need a second round-trip.

Including credentials

fetch(url, { credentials: "include" });

By default, fetch does NOT send cookies on cross-origin requests. credentials: "include" opts in. The server must respond with Access-Control-Allow-Credentials: true for the browser to accept.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.