Belajar
← Semua pelajaran

Cara kerja request HTTP

Satu request, satu response

Browser
api.shop.test

request.http

// baris pertama: method, path, versiPOST /notes HTTP/1.1Host: api.shop.testContent-Type: application/jsonContent-Length: 19// baris kosong menutup header {"text":"buy eggs"}

server.js

app.post("/notes", (req, res) => {  const note = create(req.body.text);  res.status(201)    .location(`/notes/${note.id}`)    .json(note);});

Kirim request buatanmu ke API catatan kecil

MethodGETPOSTPUTDELETEPath
Body

Route: /notes dan /notes/:id. Catatan 1 dan 2 sudah ada

Request
Response

server.js

app.use(express.json()); // body yang bukan JSON langsung dapat 400 di siniapp.get("/notes", (req, res) => res.json(all()));app.post("/notes", auth, (req, res) => {  if (!req.body?.text) return res.sendStatus(400);  const note = create(req.body.text);  res.status(201).location(`/notes/${note.id}`).json(note);});app.all("/notes", (req, res) => res.set("Allow", "GET, POST").sendStatus(405)); app.get("/notes/:id", (req, res) => {  const note = find(req.params.id);  if (!note) return res.sendStatus(404);  res.json(note);});app.put("/notes/:id", auth, (req, res) => res.json(replace(req)));app.delete("/notes/:id", auth, (req, res) => res.sendStatus(204));app.all("/notes/:id", (req, res) => res.set("Allow", "GET, PUT, DELETE").sendStatus(405)); app.use((req, res) => res.sendStatus(404));

auth.js

function auth(req, res, next) {  if (!req.headers.authorization) {    res.set("WWW-Authenticate", "Bearer");    return res.sendStatus(401);  }  next();}

Membaca status code digit pertama menunjukkan siapa yang salah

Status code
Status line
arti
kelas
Ketik kode dari 100 sampai 599

Status 200 berisi pesan error merusak semua ini. Klien, cache, dan retry semuanya percaya pada kodenya

client.js

// fetch mengikuti 301, 302, 303, 307, dan 308 untukmuconst res = await fetch("/notes/1");if (res.ok) return res.json(); // 200 sampai 299// 4xx: ubah request-nya sebelum mencoba lagiif (res.status < 500) throw new Error(res.status);// 5xx: request yang sama mungkin berhasil nantireturn retryLater(res);

Topik

Berikutnya: Cara kerja QUIC dan HTTP/3

Buka pelajaran