Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Fetch Fundamentals

Sending Data: POST, PUT, PATCH, DELETE

Send data with fetch: set the method, send JSON, form-encoded and FormData bodies, set Content-Type, use Request objects, and see what the server receives.

So far we only asked servers for data. Real applications also change data: sign up a user, save a post, rename a file, remove a comment. With fetch, that means passing a second argument, an options object, that sets the HTTP method, optional headers and an optional body.

The methods have conventional meanings (covered in HTTP for AJAX Developers): POST creates, PUT replaces, PATCH partially updates and DELETE removes. This lesson shows how to send each one, and how to format the body so the server understands it.

Since our sandbox cannot reach a real server, the examples talk to a small mock server function. It receives a genuine Request object, exactly the object a real server framework would parse, and reports what it saw. That lets you watch what fetch really sends. Calls to real servers are shown read-only.

The options object

JavaScript
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada' }),
});
Option Purpose
method GET (default), POST, PUT, PATCH, DELETE, ...
headers Extra request headers as an object, array of pairs, or Headers
body The data to send (string, FormData, URLSearchParams, Blob, ...)

A GET or HEAD request cannot have a body. If you try, fetch throws a TypeError.

sequenceDiagram
  participant App as Your code
  participant Server
  App->>Server: POST /users<br/>Content-Type: application/json<br/>{"name":"Ada"}
  Server-->>App: 201 Created<br/>{"id":42,"name":"Ada"}

A POST carries a body and tells the server how to read it with Content-Type.

A mock server to look inside requests

This helper builds a Request from whatever fetch would receive, then answers based on the content type. We reuse it in the examples below.

JS Sending JSON with POST

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three things must all line up for JSON to work: the method, a Content-Type: application/json header, and a body that is a string you made with JSON.stringify. Passing the object directly (body: user) sends the text [object Object].

JS What goes wrong without the header

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the second case the server sees text/plain;charset=UTF-8. Many frameworks will refuse to parse that as JSON and leave the request body empty, which produces confusing "missing field" errors.

PUT, PATCH and DELETE

The mechanics are identical; only the method (and the meaning) changes.

  • PUT sends the complete new version of a resource. Fields you leave out are expected to be removed or reset.
  • PATCH sends only the fields that change.
  • DELETE usually has no body.
JS PUT, PATCH and DELETE against an in-memory store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the two updates. PATCH kept the email and changed the name; PUT replaced the whole record, so the email disappeared. A successful DELETE often returns 204 No Content with an empty body, so do not call response.json() on it.

Form-encoded bodies

HTML forms send application/x-www-form-urlencoded by default: name=Ada&lang=js, with special characters percent-encoded. Use URLSearchParams to build it. When you pass one as the body, fetch sets the right Content-Type for you.

JS URLSearchParams body

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how the space became +, & became %26 and = became %3D. Building such strings by hand with + concatenation is error-prone, so let URLSearchParams do it.

FormData and file uploads

FormData builds a multipart/form-data body, the format for forms with file inputs. Pass it as the body and do not set Content-Type yourself: the browser must add the boundary value that separates the parts, and you cannot know it in advance.

JS FormData with a file

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can also build FormData straight from a <form> element with new FormData(formElement); Submitting Forms with AJAX goes further.

Request objects

Instead of passing a URL plus an options object, you can build a reusable Request and give it to fetch. This is handy when you want to prepare a request, inspect it, or re-send it with small changes.

JS Building and cloning a Request

Press Run (or Ctrl + Enter) to see the console output here.

No output.

As with a Response, a request body can be read only once. A request whose body has been consumed cannot be sent again, which matters for retries (see Retries, Backoff and Resilience). Keep the original data around and build a fresh Request for each attempt.

Real servers (read-only)

Against a real API, the same code looks like this. It is not runnable in the sandbox:

JavaScript
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada' }),
});

if (!response.ok) throw new Error('HTTP ' + response.status);
const created = await response.json();

Cross-origin requests with a JSON Content-Type trigger a CORS preflight (an OPTIONS request the browser sends first), so the server must allow them. That is explained in Headers, Auth and CORS Basics. Always check response.ok, as in Handling Errors in fetch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct way to send an object as JSON with fetch?

    The body must be a string, and the Content-Type header tells the server to parse it as JSON. A plain object becomes the useless text [object Object].
  2. 2. What is the difference between PUT and PATCH?

    PUT sends the complete new version. PATCH sends a partial change that is merged into the existing resource.
  3. 3. Why should you not set Content-Type manually when the body is FormData?

    multipart/form-data needs a boundary string chosen by the browser. If you set the header yourself, the boundary is missing and the server cannot split the parts.
  4. 4. A successful DELETE responds with 204. What should your code avoid?

    204 No Content has no body, so json() would reject. Check the status before parsing.
  5. 5. What does passing a URLSearchParams object as body do?

    fetch recognizes URLSearchParams, encodes it as key=value pairs and sets the form-urlencoded content type for you.

Summary

  • Pass { method, headers, body } as the second argument to fetch; GET and HEAD cannot have bodies.
  • JSON needs the right method, Content-Type: application/json and a JSON.stringify string body.
  • PUT replaces, PATCH merges, DELETE removes (often answering 204 with no body).
  • URLSearchParams makes form-encoded bodies; FormData makes multipart bodies and needs no manual Content-Type.
  • A Request object bundles URL, method, headers and body; its body is one-time, so clone or rebuild it to retry.
  • Mock servers that receive real Request objects let you inspect exactly what is sent.

Next: Headers, Auth and CORS Basics.