A couple of examples of sending a request to the server

Good day, friends!

When developing web applications, it is often necessary to obtain data from the server.

There are many ways to do this in JavaScript today.

Let's see how XMLHttpRequest, Fetch, and Axios are used in practice.

The tasks will use the JSONPlaceholder - a fake online REST API for testing and prototyping (in other words, a training database).

XMLHttpRequest


Task: get a list of users and display this list in the console.

Decision:

//   XMLHttpRequest   
let xhr = new XMLHttpRequest()

//  
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')

//  
xhr.send()

/*xhr.onload = function() {
    if (xhr.status != 200) {
        console.log(`error ${xhr.status}:${xhr.statusText}`)
    } else {
        console.table(JSON.parse(xhr.response))
    }
}*/

//  
//   ,    
//  ,       
xhr.onload = () => xhr.status != 200 ? console.error(xhr.status) : console.table(JSON.parse(xhr.response))

//   
//     Content-Length,     
//   ,     
xhr.onprogress = event => {
    if (event.lengthComputable) {
        console.dir(`received ${event.loaded} of ${event.total} bytes`)
    } else {
        console.dir(`received ${event.loaded} bytes`)
    }
}

//   
xhr.onerror = () => console.error('error')

Result:



Code on GitHub .

Fetch


Task: similar.

Solution (compare with XMLHttpRequest):

fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => console.table(json))
    .catch(error => console.error(error))

Result:



Code on GitHub .

Or if you like async / await more:

(async () => {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
        const data = await response.json()
        console.table(data)
    } catch (error) {
        console.error(error)
    } finally {
        console.log('done')
    }
})()

Result:



Code on GitHub .

Let's complicate the task a bit: now you need to get images from the server and form a gallery from them.

Decision:

const url = 'https://jsonplaceholder.typicode.com/photos/'

getPhotosAndMakeGallery(url)

function getPhotosAndMakeGallery(url) {
    for (let i = 1; i < 11; i++) {
        fetch(url + i)
            .then(response => response.json())
            .then(photo => {
                let img = document.createElement('img')
                img.src = photo.url
                document.body.append(img)
            })
    }
}

Result:



Code on GitHub .

Axios


To connect this library, you need to add <script src = " unpkg.com/axios/dist/axios.min.js "> </script> in the head of the document.

Task: get the list of users and display it in the console.

Decision:

axios.get('https://jsonplaceholder.typicode.com/users')
    .then(response => console.table(response.data))
    .catch(error => console.log(error))

GitHub code .

Or if you prefer async / await:

(async () => {
    try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        console.table(response.data);
    } catch (error) {
        console.error(error);
    }
})()

GitHub code .

We complicate the task: get todos and create a list.

Decision:

const url = 'https://jsonplaceholder.typicode.com/todos/'

getTodosAndMakeList()

function getTodosAndMakeList() {
    const ul = document.createElement('ul')
    document.body.append(ul)

    for (let i = 1; i < 21; i++) {
        axios.get(url + i)
            .then(response => {
                let li = document.createElement('li')
                li.textContent = `title: ${response.data.title}; completed: ${response.data.completed}`
                ul.append(li)
            })
            .catch(error => console.log(error))
    }
}

Result:



Code on GitHub .

We complicate it: get users, comments and photos, combine these data and present everything in a readable form.

Decision:

function getUsers(i) {
    return axios.get('https://jsonplaceholder.typicode.com/users/' + i)
}

function getComments(i) {
    return axios.get('https://jsonplaceholder.typicode.com/comments/' + i)
}

function getPhotos(i) {
    return axios.get('https://jsonplaceholder.typicode.com/photos/' + i)
}

(async() => {
    for (let i = 1; i < 7; i++) {
        let request = await axios.all([getUsers(i), getComments(i), getPhotos(i)])
            .then(axios.spread(function(user, comment, photo) {
                let figure = document.createElement('figure')
                document.body.append(figure)
                let figcaption = document.createElement('figcaption')
                figcaption.textContent = `Post ${i}`
                figure.append(figcaption)

                let img = document.createElement('img')
                img.src = photo.data.url
                figure.append(img)

                let userName = document.createElement('p')
                userName.innerHTML = `<span>Name:</span> ${user.data.username}`
                figure.append(userName)

                let userComment = document.createElement('p')
                userComment.innerHTML = `<span>Comment:</span> ${comment.data.body}`
                figure.append(userComment)
            }))
    }
})()

Result:



Code on GitHub .

Thank you for attention.

All Articles