xxxxxxxxxx
// //!FETCH API
const getTurkey = () => {
let url = "https://restcountries.com/v3.1/name/benin";
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.then((data) => printData(data));
};
const printData = (countryData) => {
const {
name: { common: countryName },
capital,
region,
population,
flags: { svg: flagImage },
currencies,
} = countryData[0];
console.log(countryName, capital, region, population, flagImage);
document.getElementById(
"countryDiv"
).innerHTML = ` <img src="${flagImage}" width="300px">
<h2>${countryName}</h2>
<p>${capital}</p>
<p>${region}</p>
<p>${population}</p>`;
console.log(Object.values(currencies));
const [{ name: manyName, symbol }] = Object.values(currencies);
console.log(manyName, symbol);
};
getTurkey();
//!2
const getAll = () => {
let url = "https://restcountries.com/v3.1/all";
fetch(url)
.then((res) => res.json())
.then((data) => printData(data))
.catch((err) => console.log(err));
};
const printData = (data) => {
data.forEach((country) => {
const {
name: { common },
region,
population,
capital,
currencies,
flags: { svg: flagImage },
} = country;
const countryDiv = document.querySelector("#countryDiv");
countryDiv.innerHTML += ` <img src="${flagImage}" width="300px">
<h2>Country: ${common}</h2>
<h2>Capital: ${capital}</h2>
<h2>Region: ${region}</h2>
<h2>Population: ${population}</h2>`;
});
};
getAll();
xxxxxxxxxx
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
xxxxxxxxxx
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
xxxxxxxxxx
//Obj of data to send in future like a dummyDb
const data = { username: 'example' };
//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
console.error('Error:', error);
});
//
xxxxxxxxxx
const options = {method: 'GET', headers: {Accept: 'application/json'}};
fetch('https://api.test.com/data/id', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
xxxxxxxxxx
// Get
fetch('<your-url>')
.then((response) => response.json()).then(console.log).catch(console.warn);
// POST, PUT
data = "your data"
fetch('<your-url>', {
method: 'POST', // or 'PUT'
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
.then(response => response.json()).then(console.log).catch(console.warn);
xxxxxxxxxx
// Error handling while fetching API
const url = "http://dummy.restapiexample.com/api/v1/employee/40";
fetch(url) //404 error
.then( res => {
if (res.ok) {
return res.json( );
} else {
return Promise.reject(res.status);
}
})
.then(res => console.log(res))
.catch(err => console.log('Error with message: ${err}') );
xxxxxxxxxx
const fetch = require('node-fetch');
let response = await fetch(`your url paste here`, {
headers: {
Authorization: `Token ${API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
method: 'POST',
});
const results = await response.json();
console.log("======> :: results", results);
xxxxxxxxxx
fetch('https://apiYouWantToFetch.com/players') // returns a promise
.then(response => response.json()) // converting promise to JSON
.then(players => console.log(players)) // console.log to view the response
xxxxxxxxxx
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
xxxxxxxxxx
fetch('http://example.com')
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.error(err));
/* for JSON, use response.json() on the 2nd line */