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://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"]);}