Request options, JSON bodies & server validation

Send data with POST

Lesson 15 of 20 · 13 min · Module 4: Talk to a server

Pages also send data: a comment, an order, a message. A POST request carries that data to the server, which answers with the result or with what needs fixing.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Send JSON with a POST request
  • Read the server’s answer for success and errors
  • Prevent double submissions

The idea

Pass an options object as the second argument: method: 'POST', a headers object with 'Content-Type': 'application/json', and a body made with JSON.stringify. Servers often answer validation problems with status 422 and a JSON body describing the error, so read the body in both cases.

const response = await fetch('/api/messages', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ text: 'Hello' }),
});
const result = await response.json();

01The request has three parts

The method says what to do, the headers describe the body, and the body carries the data. Without the Content-Type header, many servers do not know how to read the JSON.

fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data),
});

02Errors come with explanations

A 422 response is not a crash: it is the server telling people what to fix. Showing body.error, and keeping what they typed, lets them correct it in seconds.

03One click, one request

Disabling the button while sending prevents duplicate orders and comments when people click twice. finally guarantees it is enabled again, whatever happened.

Your turn

On submit of #feedback: prevent the default and disable #send. POST to /api/feedback with the header Content-Type: application/json and the JSON body { "rating": 5, "comment": "…" } (the rating as a number). Read the JSON answer: if response.ok, show its message in #result and reset the form; otherwise show its error and keep the form. If the request fails completely, show Could not send your feedback. Check your connection. In every case, enable the button again at the end.

What the checks look for

  • It sends a POST request with a JSON body
  • The server’s message is shown and the form cleared
  • The button is disabled while sending
  • Validation errors from the server are shown
  • A lost connection is explained
  • An empty comment is never sent
Try it in the editor →

Take this with you

POST JSON, read the answer, and keep the interface honest while waiting.

Go a little further

Show a character counter for the comment and disable the button until there are at least 10 characters.

Learn JavaScript in the Browser for free

20 short lessons with real code and instant checks.

See the whole course →