🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Sending Data with fetch

A POST request sends data to a server. fetch sends a POST when the options object carries a method of POST.

A first POST

The options object sets the method to POST. The body carries the user object as a JSON string.

(async () => {
  const response = await fetch("data:application/json,%7B%22saved%22%3Atrue%7D", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Ana", age: 30 })
  });
  const data = await response.json();
  console.log(data.saved);
})();

The body as JSON

JSON.stringify turns an object into a JSON string. That string is what the body carries.

const user = { name: "Ana", age: 30 };
console.log(JSON.stringify(user));

Reading the POST answer

A POST still returns a response. The code reads the id from the answer.

(async () => {
  const response = await fetch("data:application/json,%7B%22id%22%3A7%7D", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "New note" })
  });
  const data = await response.json();
  console.log(data.id);
})();

Example

(async () => {
  const note = { title: "Shopping", done: false };
  const response = await fetch("data:application/json,%7B%22created%22%3Atrue%2C%22id%22%3A42%7D", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(note)
  });
  const data = await response.json();
  console.log(data.created);
  console.log(data.id);
})();

Key points

  • POST: a request method that sends data instead of asking for it
  • Options object: the second argument to fetch, which carries the method, the headers, and the body
  • Headers: extra details sent with a request, like the body format
  • Content-Type: a header that names the format of the body
  • JSON.stringify: a function that turns a value into a JSON string
  • The body of a POST is often a JSON string.

In this example, the note object holds the data to send. JSON.stringify turns the note into a JSON string for the body. The response confirms the note was created with the id 42.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Where do the method and headers go in a fetch call?