Start learning free

LESSON 8 OF 173 · BACKEND: HOW THE WEB WORKS

Send Data with POST

Practice

Every request has a method, the verb that says what it does. GET asks for something and changes nothing. POST sends data to the server so it can create something new.

fetch sends a GET unless you say otherwise. For a POST, pass an object with three options after the address: method: "POST"; headers with Content-Type: application/json, so the server knows how to read the body; and body, the text to send. JSON.stringify turns an object into JSON text. For example, to send a note to a notes service:

const note = { text: "Call the supplier", pinned: true };
const reply = await fetch("https://notes.example/notes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(note),
});

When a POST creates something, the server answers 201 Created, not 200, and the body usually describes what it made, with the id it gave it. Each POST changes the server: send two, and you create two things. Your script orders 3 mugs (product 1), then 10 pens (product 4):

POST /orders  {"product_id": 1, "quantity": 3}   →  201  {"order_id": 1001, "product_id": 1, "quantity": 3}
POST /orders  {"product_id": 4, "quantity": 10}  →  order_id 1002
Status: 201
Order placed: 1001
Order placed: 1002

Your task: POST an order for 3 of product 1 as JSON to /orders, and print the status and the new order's id. Then POST a second order, 10 of product 4, and print its id.


Assignment
Follow the Coding Tutorial to place two orders with the supplier and read what it created.


Hint
fetch takes the address, then an object with method, headers and body; JSON.stringify makes the body's text. The answer's body is JSON: read it with await response.json() and take its order_id.


STEP 1 OF 12
    Ctrl + Enter to check