const data ={username:'example'};fetch('https://example.com/profile',{method:'POST',// or 'PUT'headers:{'Content-Type':'application/json',},body:JSON.stringify(data),}).then(response=> response.json()).then(data=>{console.log('Success:', data);}).catch((error)=>{console.error('Error:', error);});
Thefetch() method inJavaScript 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));
//Obj of data to send in future like a dummyDbconst data ={username:'example'};//POST request with body equal on data in JSON formatfetch('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);});//
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 */
constloadData=()=>{const url =`...URL...`;fetch(url).then(res=> res.json()).then(data=>console.log(data)).catch(error =console.log(error))};loadData();// See Results On Browser Consol
// Example POST method implementation:asyncfunctionpostData(url ='', data ={}){// Default options are marked with *const response =awaitfetch(url,{method:'POST',// *GET, POST, PUT, DELETE, etc.mode:'cors',// no-cors, *cors, same-origincache:'no-cache',// *default, no-cache, reload, force-cache, only-if-cachedcredentials:'same-origin',// include, *same-origin, omitheaders:{'Content-Type':'application/json'// 'Content-Type': 'application/x-www-form-urlencoded',},redirect:'follow',// manual, *follow, errorreferrerPolicy:'no-referrer',// no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-urlbody:JSON.stringify(data)// body data type must match "Content-Type" header});return response.json();// parses JSON response into native JavaScript objects}postData('https://example.com/answer',{answer:42}).then(data=>{console.log(data);// JSON data parsed by `data.json()` call});
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
// Getfetch('<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);
// Making get requestsconst url ="http://dummy.restapiexample.com/api/v1/employees";fetchurl().then(res=>{console.log(res);}).catch(err=>{console.log('Error: ${err}');});
fetch('https://pokeapi.co/api/v2/pokemon/').then(function(response){return response.json();// This returns a promise!}).then(function(pokemonList){console.log(pokemonList);// The actual JSON response}).catch(function(){// Error});
asyncfunctionsendMe(){let r =awaitfetch('/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 argumentfetch("test.json").then(response=>{return response.json();}).then(data=>{document.body.innerHTML= data.name;console.log(data)}).catch(error=>{console.error(error)})