Advertisement
Beginner JavaScript, Networking: Fetch, XHR, WebSockets & CORS

How do you send a POST request with a JSON body using fetch()?

Short answer

Pass an options object as the second argument specifying method: 'POST', a Content-Type header, and a JSON.stringify()'d body — fetch doesn't set the Content-Type header automatically for you.

Save JavaScript mock interview
Advertisement
AModel answer
Pass an options object as the second argument specifying method: 'POST', a Content-Type header, and a JSON.stringify()'d body — fetch doesn't set the Content-Type header automatically for you.
await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Sam' })
});
Real-world example
Submitting a new user registration form's data to a backend API.
Likely follow-ups
  • What happens if you forget to set the Content-Type header?
Related topics