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 */
fetch('https://example.com/path',{method:'GET',headers:{'Authorization':'Basic '+btoa('login:password')//use btoa in js and Base64.encode in node}}).then(response=> response.json()).then(json=>console.log(json));
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"]);}
fetch('https://shazam.p.rapidapi.com/search?term=kiss%20the%20rain&locale=en-US&offset=0&limit=5',{// request methodmethod:'GET',// headers from the API documentationheaders:{'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