DEV Community

Cover image for JavaScript And Fetch
Kiran Raj R
Kiran Raj R

Posted on • Updated on

JavaScript And Fetch

"The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.", as per MDN documents

JavScript can send network requests to the server to get information using different methods one of such method is using the fetch method of the Fetch API, It is not supported in IE browsers, you can check the support of fetch here.

Is Fetch Fetch part of JavaScript? No, it is not a part of JavaScript, it is the part of the Web Platform API and other underlying web standards.

The fetch() method help us to fetch resources asynchronously, it will takes one mandatory argument, a path of the resource that we need to fetch. The fetch method always returns a promise, "Not data" but a promise. The initial state will be pending and it may go into fulfilled or rejected based on the successfulness of the fetch operation.

//syntax
let result = fetch(url, options)
Enter fullscreen mode Exit fullscreen mode
  1. url represents the URL to be fetched.
  2. options represents Object that contain additional parameters the could be passed to the fetch, its optional.
let data = fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => {
        if (res.ok) {
           console.log("Data fetched");
        }// Data fetched
        return res.json()
     })
     .then(json => console.log(json.name)) //Leanne Graham
     console.log(data);
     // [[PromiseState]]: "fulfilled"
     // [[PromiseResult]]: undefined
Enter fullscreen mode Exit fullscreen mode

In the above code we try to fetch a resource, then we use a then method to handle the promise returned by the fetch, the first then method contains a if statement which checks whether the fetch was successful by checking res.ok, as it returned true, Data fetched message was displayed on the console. res.json() convert the response body into json format, that data is captured by the second then method and key with the name in the response body is printed on to the console. Remember, you need to get the response body from the promise using methods like text(), json(), formData(), blob() etc., that is the reason why we used two then statements.

fetch('https://jsonplaceholder.typicode.com/users/1')
   .then(response => { 
       console.log(response.status, response.ok); //200 true
})  

let f1 = fetch('https://jsonplaceholder.typicode.com/user')
   .then(response => { 
       console.log(response.status, response.ok); //404 false
})
.catch(error => console.log("Error", error))

console.log(f1);
//[[PromiseState]]: "fulfilled"
//[[PromiseResult]]: undefined

// Code inside catch method did not execute as , no 
// rejection occurred.
Enter fullscreen mode Exit fullscreen mode

Take a look at the second fetch in the above code, the code returned response.ok with a false and response.status with 404 but the state of the promise was fulfilled, fetch method won't reject on HTTP error status like 404 or 500.

Some response properties

fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => {
    console.log(response.ok, response.status); 
    // true 200
    console.log(response.headers.get('Content-Type'));
    // application/json; charset=utf-8
    return response
}) 
Enter fullscreen mode Exit fullscreen mode
  1. response.ok: Returns true if the HTTP status code is anything from 200 to 299.
  2. response.status: Returns the HTTP status code.
  3. response.headers: Returns HTTP response header.

We can pass object with header configurations as a second parameter to the fetch to set header options in the fetch call.

Methods to read response body

There are various promise based methods to access the body, some of them are explained below.

1. response.text()

Read and return the response body in the text format


fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => {
         console.log( response.ok, response.status );  
         // true 200
         return response.text();
     })
     .then(text => { console.log(typeof text) // string
           console.log(text); 
     })

//                  Output of console.log(text)
// {
//   "id": 1,
//   "name": "Leanne Graham",
//   "username": "Bret",
//   "email": "Sincere@april.biz",
//   "address": {
//     "street": "Kulas Light",
//     "suite": "Apt. 556",
//     "city": "Gwenborough",
//     "zipcode": "92998-3874",
//     "geo": {
//       "lat": "-37.3159",
//       "lng": "81.1496"
//     }
//   },
//   "phone": "1-770-736-8031 x56442",
//   "website": "hildegard.org",
//   "company": {
//     "name": "Romaguera-Crona",
//     "catchPhrase": "Multi-layered client-server neural-net",
//     "bs": "harness real-time e-markets"
//   }
// }

Enter fullscreen mode Exit fullscreen mode

2. response.json()

Read and return the response body as json format

fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => {
         console.log(response.ok, response.status);  
          //true 200
         return response.json();})
     .then(json => { 
          console.log(typeof json)// object
          console.log(json);})


//               Output of console.log(json)
// {          
// address:
//     city: "Gwenborough"
//     geo:
//         lat: "-37.3159"
//         lng: "81.1496"
//     street: "Kulas Light"
//     suite: "Apt. 556"
//     zipcode: "92998-3874"
// company:
//     bs: "harness real-time e-markets"
//     catchPhrase: "Multi-layered client-server neural-net"
//     name: "Romaguera-Crona"
// email: "Sincere@april.biz"
// id: 1
// name: "Leanne Graham"
// phone: "1-770-736-8031 x56442"
// username: "Bret"
// website: "hildegard.org"  
Enter fullscreen mode Exit fullscreen mode

3. response.formData()

Read and return the response body as FormData object

<form action="" id="form1" name="form1">
   <input type="text" name="fname" placeholder= 
      "FirstName">
   <br>
   <input type="text" name="lname" placeholder= 
       "LastName">
   <br>
   <Button id="submit">Submit</Button>
</form>
// I provided "kiran" as value for first input and "raj"
// as value for second input. 

<script>
   const btn = document.getElementById('submit');
   const form1 = document.getElementById('form1');
   let formData1;

   btn.addEventListener('click', (e)=>{

     e.preventDefault();
     let data = new FormData(form1);
     const obj =  Object.fromEntries(data.entries());

     fetch( 'https://jsonplaceholder.typicode.com/posts' 
        ,{
            method: 'POST',
            body: JSON.stringify(obj),
            headers: {
              'Content-type': 'application/json; 
               charset=UTF-8'
            }
      })
      .then((response) => response.text())
      .then((text) => console.log(text));

})
</script>

//Output
//{
//  "fname": "kiran",
//  "lname": "raj",
//  "id": 101
//}
Enter fullscreen mode Exit fullscreen mode

Remember only one method can be used to read the response or error body as the content has been already read by the first method.

I just skim through the basics of fetch method, will update with more examples and information. Please feel free to comment any information you have about fetch. Suggestions are always welcomed, and if you find any mistakes, please leave a comment. Happy coding

Let's learn together :)

Top comments (5)

Collapse
 
raddevus profile image
raddevus • Edited

I love the fetch() api. It's really great and makes async calls so much easier than in past with xhr. I tried your code from the browser console.

Here's one that you can try in the browser console (F12).

fetch( 'https://jsonplaceholder.typicode.com/posts' 
        ,{
            method: 'POST',
            body: JSON.stringify({first:50}),
            headers: {
              'Content-type': 'application/json',
               'charset':'UTF-8'
            }
      })
      .then((response) => response.text())
      .then((text) => console.log(text));
Enter fullscreen mode Exit fullscreen mode

Just copy and paste into the console and hit ENTER.

Also, if you change that response.text() to response.json() you get a nice JSON object back.

console output

Collapse
 
kiranrajvjd profile image
Kiran Raj R

I need to get data from the form fields and input it into the fetch to post the data to the site, that's why I use the last example code block and I forget to explain it. I love the simplicity of your code and its a good way to show the examples, clean, thank you

Collapse
 
kiranrajvjd profile image
Kiran Raj R

I think of using async / await but then I think it will add a bit more complexity to the examples as many may not be aware of the working of async/await, so I stick with the then method. Thank you for the suggestion, i am planning to have a second part to this one, in that i will definitely use async/await.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
kiranrajvjd profile image
Kiran Raj R

No idea about php, just downloaded the image from unsplash :)