Sending GET Request Using Fetch

Hello everybody, today, we’ll discuss sending GET requests using fetch;

What’s GET request

GET: is a request used for getting or retrieving data or information from a specified server.

Code using then and catch

const getTodo …


This content originally appeared on DEV Community and was authored by Aya Bouchiha

Hello everybody, today, we'll discuss sending GET requests using fetch;

What's GET request

GET: is a request used for getting or retrieving data or information from a specified server.

Code using then and catch

const getTodo = (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    fetch(url)
        .then((response) => response.json())
        .then((todo) => console.log(todo))
        .catch((e) => console.log('something went wrong ;(', e));
};
getTodo(1);

Code using async and await

Method 1

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);

Method 2

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const data = await (await fetch(url)).json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);

Suggested Posts

To Contact Me:

Happy codding!


This content originally appeared on DEV Community and was authored by Aya Bouchiha


Print Share Comment Cite Upload Translate Updates
APA

Aya Bouchiha | Sciencx (2021-08-18T00:03:17+00:00) Sending GET Request Using Fetch. Retrieved from https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/

MLA
" » Sending GET Request Using Fetch." Aya Bouchiha | Sciencx - Wednesday August 18, 2021, https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/
HARVARD
Aya Bouchiha | Sciencx Wednesday August 18, 2021 » Sending GET Request Using Fetch., viewed ,<https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/>
VANCOUVER
Aya Bouchiha | Sciencx - » Sending GET Request Using Fetch. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/
CHICAGO
" » Sending GET Request Using Fetch." Aya Bouchiha | Sciencx - Accessed . https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/
IEEE
" » Sending GET Request Using Fetch." Aya Bouchiha | Sciencx [Online]. Available: https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/. [Accessed: ]
rf:citation
» Sending GET Request Using Fetch | Aya Bouchiha | Sciencx | https://www.scien.cx/2021/08/18/sending-get-request-using-fetch/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.