How to Fetch data from API code example
Example 1: javascript fetch api post
fetch('https://example.com/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
'foo': 'bar'
}),
})
.then((res) => res.json())
.then((data) => {
})
.catch((err) => console.log(err));
Example 2: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 3: get data from fetch api into variable
<script>
function getFromAPI(url, callback){
var obj;
fetch(url)
.then(res => res.json())
.then(data => obj = data)
.then(() => callback(obj))
}
getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);
function getData(arrOfObjs){
var results = "";
arrOfObjs.forEach( (x) => {
results += "<p> Id: " + x.id + "<ul>"
Object.keys(x).forEach( (p) => {
results += "<li>" + (p + ": " + x[p]) + "</li>";
});
results += "</ul> </p> <hr>"
})
results += "";
document.getElementById("myDiv").innerHTML = results;
}
</script>
Example 4: How to Use the JavaScript Fetch API to Get Data
fetch('http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=221380')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
Example 5: get data from api in javascript
const GetData = [];
useEffect(() => {
fetch(API_URL)
.then((res) => res.json())
.then((data) => {
GetModesData.push(...data);
setDataState(GetData.map((d) => d.modeName));
});
}, []);
Example 6: get data from fetch response html
fetch('/about').then(function (response) {
return response.text();
}).then(function (html) {
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var img = doc.querySelector('img');
console.log(img);
}).catch(function (err) {
console.warn('Something went wrong.', err);
});