What is API
API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other
What is Fetch API
Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers
let response = fetch(url);
Fetch returns a promise. Zato možemo koristiti then()
fetch(url)
.then((response) => {
// handle the response
})
.catch((error) => {
// handle the error
});
const url = "https://jsonplaceholder.typicode.com/todos/";
fetch(url)
.then(response => response.json())
.then(json => console.log(json))
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/');
let data = await response.json();
console.log(data);
}
fetchData()
const url = "https://jsonplaceholder.typicode.com/todos/1";
fetch(url)
.then(response => response.json())
.then(json => console.log(json))
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let data = await response.json();
console.log(data);
}
fetchData();
fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify({
title: 'Potato head',
completed: true,
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
completed: false,
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
let data = await response.json();
console.log(data);
}
fetchData()
fetch('https://jsonplaceholder.typicode.com/todos/1', {
method: 'PUT',
body: JSON.stringify({
title: 'foo',
completed: true,
userId: 2,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
body: JSON.stringify({
title: 'foo',
completed: false,
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
let data = await response.json();
console.log(data);
}
fetchData();
fetch('https://jsonplaceholder.typicode.com/todos/1', {
method: 'DELETE',
}).then((res) => console.log(res))
async function deletehData() {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE',
});
let data = await response;
console.log(data)
}
deleteData();
Pročitaj članke
Pogledaj video