The fetch() method in JavaScript is used to request to the server and load
the information on the webpages. The request can be of any APIs that return
the data of the format JSON or XML.
This method returns a promise.
fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));
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 */
//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);
});
//
// Update fields in form based on API GET request
function update_form_fields(term, field){
fetch("/api/profiles/?format=json")
.then((response)=>{
return response.json();
}).then((data) => {
let profile = data.find(el => el[field] == term);
document.getElementById("name-input").value = profile.name;
document.getElementById("email-input").value = profile.email;
});}
async function sendMe()
{
let r =await fetch('/test', {method: 'POST', body: JSON.stringify({a:"aaaaa"}), headers: {'Content-type': 'application/json; charset=UTF-8'}})
let res = await r.json();
console.log(res["a"]);
}
//feth method
// - take the url as parameter
// - return a promise
// - pass response when resolved
// - pass error when rejected
// - the response has the http response information
// - use the .json() is used to get the body of the response
// - .json return a promise
// - resolve the promise with data as the argument
fetch("test.json")
.then(response =>{
return response.json();
}).then(data=>{
document.body.innerHTML = data.name;
console.log(data)
}).catch(error =>{
console.error(error)
})
fetch('https://shazam.p.rapidapi.com/search?term=kiss%20the%20rain&locale=en-US&offset=0&limit=5', {
// request method
method: 'GET',
// headers from the API documentation
headers: {
'X-RapidAPI-Key': '8bd90c4cffmsh2788964981ec641p113417jsn3d0aff3880f5',
'X-RapidAPI-Host': 'shazam.p.rapidapi.com'
}
})
.then((result) => result.json()) // result from API endpoint
.then((data) => console.log(data)) // result in json format
.catch((error) => console.log(error)); // catching the error should it occur