JS fetch()
Published: (May 6, 2026 at 01:06 AM EDT)
2 min read
Source: Dev.to
Source: Dev.to
What is fetch()
fetch()is a built‑in function used to make network/HTTP requests.- It returns a Promise.
- The Promise resolves with a Response object representing the server’s response.
- You can then check the request status and extract the body of the response in various formats, such as text or JSON.
HTTP Methods
- GET – retrieve data
- POST – create data
- PUT – update data
- DELETE – delete data
Syntax
fetch(url, options)
url→ API endpointoptions→ method, headers, body, etc.
Calling fetch(url) sends the request and returns a Promise.
fetch(url)
.then(response => {
// response contains status (200, 404…), headers, body (not readable yet)
});
Reading the body
response.json() // converts body to a JavaScript object (returns a Promise)
response.text() // returns body as plain text (returns a Promise)
Basic GET request
// Get JSON data
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err));
// Get plain text
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.log(err));
Handling errors
fetch("https://jsonplaceholder.typicode.com/post")
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));