DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

JS fetch()

What is fetch():

  • fetch() is a built-in function used to make network/HTTP requests.
  • It returns a Promise.
  • The fetch() function returns a Promise which is fulfilled 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, including text and JSON.

HTTP Methods :

GET - get data
POST - create data
PUT - update data
DELETE - delete data

Syntax : fetch(url, options)

url → API endpoint
options → method, headers, body, etc.

fetch(url) - Sends request,Returns a Promise.
.then(response => ...) response contains, status (200, 404…),headers,body -not readable yet.
response.json() - Converts body into JavaScript object,also returns a Promise.
.then(data => console.log(data)) - get data.

Basic get request :

fetch("https://jsonplaceholder.typicode.com/posts")
.then ((response)=> response.json())
.then ((data)=> console.log(data))
.catch((err)=> console.log(err));

fetch("https://jsonplaceholder.typicode.com/posts")
.then ((response)=> response.text())
.then ((data)=> console.log(data))
.catch((err)=> console.log(err));
Enter fullscreen mode Exit fullscreen mode

Handling Error :

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));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)