fetch(url)
.then((response) => {returnresponse.json()})
.then((data) => {
// enter you logic when the fetch is successful
console.log('data = ', data);
})
.catch((error) => {console.log(error)})
1.2. Server to Client : fetch-async-await
asyncfunctiongetData() {
try {
letresponse=awaitfetch(url);
letdata=awaitresponse.json();
// enter you logic when the fetch is successful
console.log('data = ', data);
returndata;
} catch(error) {console.log(error)}
}
getData();
2.1. Client to Server : fetch-then-catch
fetch(url,
{
method:'POST',
headers: {
'Accept':'application/json, text/plain, */*',
'Content-Type':'application/json' },
body:JSON.stringify( {a:7, b:0.2, str:'some string'} ),
})
.then(function (response) {returnresponse.json()})
.then(function (data) {
// enter you logic when the fetch is successful
console.log('data = ', data);
})
.catch (function (error) {console.log(error)});
2.2. Client to Server : fetch-async-await
asyncfunctionsendData() {
try {
letresponse=awaitfetch(url,
{
method:'POST',
headers: {
'Accept':'application/json, text/plain, */*',
'Content-Type':'application/json' },
body:JSON.stringify( {a:7, b:0.2, str:'some string'} )
});
letres=awaitresponse.json();
// enter you logic when the fetch is successful
console.log('res = ', res);
returnres;
} catch(error) {console.log(error)}
}
sendData()