JavaScript Fetch API: What is It and How to Use It

Javascript fetch() is a built-in API that provides an interface for fetching resources. The fetch() API is a newer and simpler way of making HTTP requests in JavaScript. A promise-based API returns a Response object representing the response to the request.

The fetch() method only has one mandatory argument: the resource URL you wish to fetch. Using fetch(), we can send an ajax or network request to any server and get the json response.

Syntax

let promise = fetch(URL, [options])

Parameters

URL: the URL to access.
options: – optional parameters: method, headers, etc.

Without options, that is the simple GET request, downloading the contents of the url.

The browser immediately starts the request and returns the promise that a calling code should use to get the final result.

Getting the response is usually a two-stage process.

First, the promise, returned by the fetch() function, resolves with the object of the inbuilt Response class as soon as the server responds with headers.

At this stage, we can check the HTTP status to see whether it is successful or not check headers, but we don’t have a body yet.

The promise rejects if the fetch() cannot make an HTTP request, e.g., network problems or no such site.

    How to Send GET Requests in JavaScript fetch

    To make a simple GET request with fetch, you need to pass in the URL endpoint as an argument

    Straightforwardly, all you do is call fetch with the URL you want; by default, the Fetch API uses the GET method so that a direct call would be like this.

    fetch('https://api.github.com/users/KrunalLathiya')
      .then(response => response.json())
      .then(data => {
           console.log(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))

    Here, we get a response, and the response is a Stream object, and the response we get is not JSON but a simple Javascript object with a series of methods that we can use further to process the data way we want.

    • clone() – This method implies that this method creates a response clone.
    • json() – This method resolves the promise with JSON.
    • redirect() – This method creates a new response but with a different URL.
    • text() – In this case, it resolves with a string.
    • arrayBuffer() – Here, we return a promise that resolves with an ArrayBuffer.
    • blob() – This is one determined with a Blob.
    • formData() returns a promise but determines with the FormData object.

    Response Metadata

    In the above example, we have seen the status of a Response object and how to parse a response as JSON. In addition, we can access other metadata like headers. So visit the following code.

    fetch('users.json').then(function(response) {
      console.log(response.headers.get('Content-Type'));
      console.log(response.headers.get('Date'));
    
      console.log(response.status);
      console.log(response.statusText);
      console.log(response.type);
      console.log(response.url);
    });

    Response Types

    You can define the mode for a fetch request such that only specific requests will resolve. The modes you can set are as follows:

    1. same-origin only succeeds for the requests for assets on the same origin, and all the other requests will reject.
    2. The CORS will allow asset requests on the exact origin and other origins, which return appropriate CORS headers.
    3. The cors-with-forced-preflight will always perform a preflight check before making an actual request.
    4. The no-cors is intended to make the requests to other origins that do not have the CORS headers and result in an opaque, but as stated, this isn’t possible in the window global scope.

    If we want to define the mode, add the options object as a second parameter in the fetch request, and define a mode in that object.

    fetch('https://facebook.com/cors-enabled/some.json', {mode: 'cors'})
      .then(function(response) {
        return response.text();
      })
      .then(function(text) {
        console.log('Request successful', text);
       })
       .catch(function(error) {
        log('Request failed', error)
       });

    Request Headers

    fetch('https://api.github.com/users/KrunalLathiya', {
      headers: new Headers({
        'User-agent': 'Mozilla/4.0 Custom User Agent'
      })
     })
     .then(response => response.json())
     .then(data => {
        console.log(data)
      })
     .catch(error => console.error(error))
    
    

    How to Send Post Requests in JavaScript fetch()

    To send a POST request using fetch(), you must specify the HTTP method name in the “method” parameter and the POST data in the “body” parameter. Additional HTTP headers can be specified in the “headers” parameter.

    postRequest('https://appdividend.com/api/v1/users', {user: 'Krunal'})
      .then(data => console.log(data)) // Result from the `response.json()` call
      .catch(error => console.error(error))
    
    function postRequest(url, data) {
      return fetch(url, {
        credentials: 'same-origin', // 'include', default: 'omit'
        method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
        body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
        headers: new Headers({
        'Content-Type': 'application/json'
      }),
     });
     .then(response => response.json())
    }

    Here, we have created a postRequest function and passed the two parameters. The first parameter is the request, and the second is the data that must be stored on the server.

    Conclusion

    JavaScript Fetch API provides a fetch() method defined on a window object, which you can use to perform requests and send them to the server. This method returns a Promise that you can use to retrieve the response to the request.

    3 thoughts on “JavaScript Fetch API: What is It and How to Use It”

    1. if interface API return customer status, for example:

      res.status == 0
      .then(/*handle something*/)

      or

      res.status == 1
      .then(/*handle something*/)

      or

      res.status == 2
      .then(/*handle something*/)

      in Fetch, how to resolve?

      Reply
    2. Nice article Krunal. One question rather doubt, is is necessary to handle error scenario with catch block here or we can pass this ownership to calling method?

      Reply

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.