Axios (XHR) and fetch

Time:2021-4-13

Axios (search arrow function)

import axios from "axios";
search = () => {
    axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
                response => {
                    console.log('successs');
                    console.log(response.data);
                },
                error => {
                    console.log('errors');
                    console.log(error);
                },
            );
}

fetch

search = () => {
        //Unoptimized version
        fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
                    response => {
                        console.log('successs');
                        console.log(response);
                        //Continue to return a promise object
                        return response.json();
                    }
                ). then (response = > {// continue then
                    console.log('successs');
                    console.log(response.data.items);
                }). Catch (error = > {// unified processing error)
                    console.log('errors');
                    console.log(error);
                });
    }

//--- optimized version (asynchronous)
 search = async () => {
     try {
            //Note: the async identifier must be added to use await external functions
            const response = await fetch(`https://api.github.com/search/users?q=${keyWord}`);
            const data = await response.json();
            console.log('request success : ', data);
        } catch (error) {
            console.log('fetch error:', error);
        }
 }

Which is better?

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]