Fetch in JavaScript. Code examples

Fetch in JavaScript. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: ES6
blank
blankblank

The Fetch API provides a simplified yet flexible and powerful tool for accessing network resources by compared to the standard XMLHttpRequest (snare).

AJAX in JavaScript. Code examples open
AJAX in JavaScript. Code examples
September 23, 2022
Roman-tk

The key element of this Fetch API is the fetch() function.

The fetch function has the following syntax:

    const fetchPromise = fetch(resource[, init])

resource – parameters of the resource that the function will access.
init – function can accept an object with additional request settings. (optional parameter)

The fetch() function returns a Promise object that receives a response after the request to the network resource is completed.

For example, let’s create a simple index.html file. Let’s add the following code to it:


<head>
    <meta charset="utf-8" />
    <title>Index</title>
</head>

<body>
    <script>
        fetch("/hello")
            .then(response => response.text())
            .then(responseText => console.log(responseText));
    </script>
</body>

The fetch() function is passed the address of the resource – in this case “/hello“.

Since fetch() returns a Promise object, we can call the then() method to get the query result.

    fetch("/hello").then(response => response.text())

The callback function is passed to the then() method, which receives a response from the server as the response parameter.

However, the server response is a complex object that encapsulates a lot of different information. As long as we interested only in the text that the server sends. And to get this text, the response.text() method is called on the response object.

The response.text() method also returns a Promise. And to get the actual text of the response, we connect the second method then(), in which we get the response text in the callback function.

In the example above, a relative path was used, but an absolute path could also be used, specifying the protocol, server and port addresses:

    fetch("http://site.com:3000/hello")
        .then(response => response.text())
        .then(responseText => console.log(responseText));

fetch с async/await

We can use async/await statements to retrieve the response. For example, let’s rewrite the previous example:

        getText();
        async function getText() {
            //get response object
            const response = await fetch("/hello");
            //retrieve the response text from the response object 
            const responseText = await response.text();
            console.log(responseText);
        }

Server response

Using the properties of the Response object, you can get various information from the received response. The Response object has the following properties:

  • body – response content as an object ReadableStream
  • bodyUsed – stores a boolean value that indicates whether the content of the response has already been consumed.
  • headers – a set of response headers as a Headers object
  • ok – stores a boolean value that indicates whether the request completed successfully (that is, if the response status code is in the range 200-299)
  • redirected – stores a boolean value that indicates whether the response is the result of a redirect
  • status – stores the response status code
  • statusText – stores the status message that corresponds to the status code
  • type – stores the response type
  • url – stores the URL. If a number of redirects occur during the request, then stores the final URL after all redirects

It’s worth noting that all of these properties are read-only.

    fetch("/hello")
        .then(response => {
            console.log(response.status);       // 200
            console.log(response.statusText);   // OK
            console.log(response.url);          // https://site.com/hello
        });

A similar example with async/await:

    async function getResponse() {

        const response = await fetch("/hello");
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.url);

    }
    getResponse();

The ok property returns true if the response status code is between 200 and 299

We can check this property before processing the response:

    fetch("/hello").then(response => {
        if (response.ok) {
            // response processing
        }
    });

Using the headers property, you can get the response headers that represent the Headers interface.

To get data from the headers, we can use one of the following methods of the Headers interface:

  • entries() – returns an iterator that allows you to iterate through all the headers
  • forEach() – iterates over the headers
  • get() – returns the value of a specific header
  • has() – returns true if a certain header is set
  • keys() – gets all the titles of the set headers
  • values() – gets all the values of the set headers

For example, let’s get all the response headers:

    fetch("/hello").then(response => {

        for (header of response.headers) {

            console.log(header[0], ":", header[1]);
        }
    });

Each heading is an array of two elements, where the first element is the title of the heading and the second is its name meaning.

Checking the header and, if present, printing its value:

    fetch("/hello").then(response => {

        const headerTitle = "date";     //header name
        if (response.headers.has(headerTitle)) {  //if there is a header
            console.log(response.headers.get(headerTitle));     //get its value
        }
    });

If a redirect occurred during the request, then the redirected property is true, and the url property stores the address at which the redirect occurred.

For example, let’s say the server redirects from “/page” to “/newpage“:

    fetch("/hello").then(response => {

        if (response.redirected) {
            console.log("There was a redirect to the address", response.url);
        }
    });

Data from response

All the data sent by the server is available in the Response object through the body property, which represents the ReadableStream object, but it’s much easier to use one of the Response object’s methods.

The Response interface provides the following methods:

  • arrayBuffer() – returns a Promise that receives the contents of the response as an ArrayBuffer object
  • blob() – returns a promise that receives the content of the response as a Blob object
  • clone() – returns a copy of the current Response object
  • error() – returns a new Response object that is associated with the network error that occurred
  • formData() – returns a Promise that receives the content of the response as a FormData object
  • json() – returns a promise that receives the content of the response as a JSON object
  • redirect() – returns a new Response object with a different URL
  • text() – returns a promise that receives the content of the response as a string of text

To get the sent text, the response.text() method is called on the response object, which returns a Promise.

    then(responseText => console.log(responseText));

Or you can use async/await

    getText();
    async function getText() {
        // get the response object
        const response = await fetch("/hello");
        // extract the response text from the response object
        const responseText = await response.text();
        console.log(responseText);
    }

Getting response as JSON

Let the server send some JSON object.
Server response user array in JSON format:

Here is the array:

    user = { name: "Alexander", age: 33 };

Let’s get this object:

    fetch("/user")
        .then(response => response.json())
        .then(user => console.log(user.name, " - ", user.age));

The json() method returns a Promise object, so in the second then() method, you can get the actual sent JSON object and access its properties.

The same example using async/await:

    getUser();

    async function getUser() {
        //get the response object
        const response = await fetch("/user");
        //extract JSON from the response object
        const user = await response.json();
        console.log(user.name, "-", user.age);
    }

Similarly, you can receive a set of objects in JSON format. Suppose the server sends an array of objects:

    const users = [
        { name: "Alexander", age: 33 },
        { name: "Timote", age: 25 },
        { name: "Sergey", age: 35 }
    ];

Let’s get this data on a web page:

    fetch("/users.json")
        .then(response => response.json())
        .then(users => users.forEach(user => console.log(user.name, " - ", user.age)));

Similarly on async/await:

    getUsers();
    async function getUsers() {

        const response = await fetch("/users.json");
        const users = await response.json();
        users.forEach(user => console.log(user.name, " - ", user.age))
    }

Loading binary data

The blob() method can be used to load binary data. Let’s take an example of images. Let’s say there is an image.png file on the server

To access the server, define the following code:

    const img = document.querySelector("img");
    fetch("/image.png")
        .then(response => response.blob())
        .then(data => img.src = URL.createObjectURL(data));

The blob() method returns a Promise object that receives the response data as a Blob object. And in the second then() method get this object.

A similar example using async/await:

    const img = document.querySelector("img");
    getImage();
    async function getImage() {
        const response = await fetch("/image.png");
        const imgBlob = await response.blob();
        img.src = URL.createObjectURL(imgBlob);
    }

Setting query parameters

As a reminder, the fetch() function can additionally accept query options as a second optional parameter:

    fetch(resource[, init])

The init object can contain the following options:

  • method – request method, such as GET, POST, PUT, etc.
  • headers – headers set in the request
  • body – request body – the data that is added to the request.
  • mode – request mode, e.g. cors, no-cors and same-origin
  • credentials – defines actions with credentials (cookies, HTTP authentication data and TLS client certificates). Takes one of the following values:
    omit: credentials are excluded from the request, and any credentials sent in response from the server are ignored
    same-origin: credentials are included only in those requests and are accepted in responses only to those requests whose address belongs to the same domain as the client’s address.
    include: credentials are included in any requests and accepted in responses to any requests
  • cache – establishes the principle of interaction with the browser cache. Possible values: default, no-store, reload,
    no-cache, force-cache и only-if-cached
  • redirect – sets how to respond to redirects. It can take the following values:
    follow: automatically apply redirect
    error: generate an error when redirecting
    manual: handle the response in a different context
  • referrer – defines the referrer of the request
  • referrerPolicy – defines the referrer policy – how referrer information will be passed in the request. Can take the following values: no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin,
    origin-when-cross-origin, strict-origin-when-cross-origin и unsafe-url
  • integrity – contains the control value of the resource
  • keepalive – allows the request to exist longer than the lifetime of the web page.
  • signal – provides an AbortSignal object and allows you to cancel the execution of the request.

Example of setting options:

    fetch("/user", {
        method: "GET",
        headers: { "Accept": "application/json" }
    })

        .then(response => response.json())
        .then(user => console.log(user));

header “Accept” – its value “application/json” says that the client accepts data in JSON format.

It’s worth noting that the headers property represents a Headers object. We can use methods on this object to set headers:

    const myHeaders = new Headers();
    myHeaders.append("Accept", "application/json");
    fetch("/user", {
        method: "GET",
        headers: myHeaders
    })
        .then(response => response.json())
        .then(user => console.log(user));

The append() method adds a specific title, the title of which is passed through the first parameter, and the value of the title is passed through the second parameter.

You can also use the set() method to set the title, and if the title has already been added, then the set() method replaces its value.

    const myHeaders = new Headers();
    myHeaders.append("Accept", "application/json"); //add an Accept header
    myHeaders.set("Accept", "text/xml");        //Change the header value
    myHeaders.delete("Accept");                 //Removing header

The body option is used to send data to the fetch() function within the second parameter. This data can be Blob, BufferSource, FormData, URLSearchParams, USVString, and ReadableStream types. It should be noted that in requests with the GET and HEAD methods, this option cannot be set for the request.

    fetch("/user", { method: "POST", body: "Alexander" })
        .then(response => response.text())
        .then(userName => console.log(userName));

We send plain text. And since the server also sends text in response, the response.text() method is used to receive the response. In a similar way, you can send data that is more complex in structure. For example, consider sending JSON. Then on the web page we get back the data using the respose.json() method:

    fetch("/user", {
        method: "POST",
        headers: { "Accept": "application/json", "Content-Type": "application/json" },
        body: JSON.stringify({
            name: "Alexander",
            age: 33
        })
    })
        .then(response => response.json())
        .then(user => console.log(user.name, "-", user.age));
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation