🌐
REST + fetch()
HTTP methods, fetch GET/POST patterns. Memorize the two-.then() chain.
HTTP methods
| Method | Purpose |
|---|---|
GET | Read data (no body) |
POST | Create new data (with body) |
PUT | Update / replace |
DELETE | Remove |
fetch — GET
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => console.log("Error:", err));fetch — POST
fetch("https://api.example.com/data", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ali", age: 25 })
})
.then(res => res.json())
.then(data => alert("Saved!"));Line-by-line meaning
fetch(url)— make the HTTP request.then(res => res.json())— parse response body as JSON.then(data => {...})— use the actual data objectJSON.stringify(obj)— convert JS object to a string for the serverheaders: {"Content-Type":"application/json"}— tells server body is JSON
Status codes
200 OK · 201 Created · 400 Bad request · 404 Not found · 500 Server error