Basic principles of API Fetch.
Website For Learn - https://developer.mozilla.org/en/docs/Web/API/Fetch_API/Using_Fetch
Methods that can be used Fetch : https://developer.mozilla.org/en/docs/Web/API/WindowOrWorkerGlobalScope/fetch
fetch can take several methods first of all : the entry then init
Promise<Response> fetch(entrée[, init]);
or
fetchResponsePromise = fetch(resource, init);
website : https://jsonplaceholder.typicode.com/
so we'll take the call to /users as an example, which returns a list of users
to make a a stroke of fetch by passing him a first parameter that will send me back a promise
EXAMPLE :
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json()).then(console.log)
EXAMPLE :
const getUsers = async function () {
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data = await response.json()
console.log(data)
}
getUsers() // returns list of users
EXAMPLE :
const getUsers = async function () {
let response = await fetch('https://jsonplaceholder.typicode.com/usersdhsgdsdjsjdsjdkdjskdj')
if (response.ok) {
let data = await response.json()
console.log(data)
}else {
console.error('server return : ', response.status)
}
}
getUsers()
const getUsers = async function () {
try {
let response = await fetch('https://127.0.0.1:4848')
if (response.ok) {
let data = await response.json()
console.log(data)
} else {
console.error('server return : ', response.status)
}
} catch (e) {
console.log(e)
}
}
getUsers()
- from link URL : https://jsonplaceholder.typicode.com/posts
EXAMPLE :
const insertPost = async function (data) {
let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify(data)
})
let responseData = await response.json()
console.log(responseData)
}
insertPost({
name: 'Marie Claire',
age: 29
})