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
- Making GET And POST Request Using Axios In React.js
- Making PUT & DELETE Request Using Axios In React.js
- Youtube Courses, Projects To Master Javascript
- Your Essential Guide To Map Built-in Object In Javascript
- All JS String Methods In One Post!
To Contact Me:
- email: developer.aya.b@gmail.com
- telegram: Aya Bouchiha
Happy codding!
This content originally appeared on DEV Community and was authored by Aya Bouchiha
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.