CodeBlanks Logo Icon CodeBlanks

POST requests

JavaScript course · Intermediate · Lesson 87/134

Learn to send a POST request with method, body and headers.

Sending data with POST

A POST request sends new data to the server. In the second parameter of fetch you pass the method, body and headers options together.

const response = await fetch(url, {
  method: 'POST',
  body: 'hello',
  headers: { 'Content-Type': 'text/plain' }
});

method sets the type of the request, and body carries the data being sent. The body can be text, but it can also be a FormData or a Blob. You also add the Content-Type header so the server can read the body correctly.

Checking the response status

After a POST request, you check the server's answer with response.status. When a new resource is created, the server usually returns 201.

const response = await fetch(url, { method: 'POST', body: 'hello' });
console.log(response.status);

A successful request gives a code in the 2xx range. 200 means a general success, 201 means a new resource was created, and 400 means a client error. You can reach the details of the answer through the body.

Exercise Make a POST request and log the status code

The url variable holds an address. Make a fetch request with { method: 'POST', body: 'hello', headers: { 'Content-Type': 'text/plain' } } as the second parameter and put the response into a response variable. Then log response.status with console.log.

Show example solution
const response = await fetch(url, {
  method: 'POST',
  body: 'hello',
  headers: { 'Content-Type': 'text/plain' }
});
console.log(response.status);

Test yourself

  1. Match options to their meanings

    method: 'POST'
    Sets the type of the request
    body: 'hello'
    Carries the data being sent
    headers: { ... }
    Holds the headers
  2. Which method is used to create a new resource on the server?

    // A
    method: 'GET'
    // B
    method: 'DELETE'
    // C
    method: 'PUT'
    // D
    method: 'POST'
    • A
    • B
    • C
    • D
    Show answer

    D — Correct! POST is used to create a new resource.

  3. Write the POST options

    const response = await fetch(url, {
      ____: 'POST',
      body: 'hello'
    });
    Show answer
    const response = await fetch(url, {
      method: 'POST',
      body: 'hello'
    });

All lessons in Intermediate