Базовый GET
fetch(url) возвращает Promise с Response. Важно: HTTP 404/500 не reject — reject на сеть, CORS, abort, битый URL. Всегда проверяйте response.ok / status.
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
POST
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json; charset=UTF-8" },
body: JSON.stringify({ title: "foo", body: "bar", userId: 1 }),
})
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(console.log)
.catch(console.error);
Плюсы для ответа
- Отмена:
AbortController.
- Тело:
json(), text(), blob(), streams.
- Современный стандарт браузера и Node.
Итог: fetch + проверка ok + разбор тела; ошибки сети ≠ ошибки HTTP-статуса.