Javascript Code
const btn = document . getElementById ( " btn " );
const divdata = document . getElementById ( " divdata " );
//Work with remote api
// Promise then | Single Data
// const makeRequest = async() => {
// console.log(1)
// fetch("http://127.0.0.1:8000/student/")
// .then((res) => {
// if (!res.ok){
// console.log(res.statusText);
// }
// return res.json();
// }).then((data) => {
// console.log(data);
// }).catch((err) => {
// console.log(err)
// })
// }
// Async & Await
// const makeRequest = async () => {
// try {
// const res = await fetch("http://127.0.0.1:8000/student/");
// if (!res.ok) {
// throw new Error(res.statusText)
// }
// const data = await res.json();
// console.log(data);
// data.forEach((item) => {
// divdata.innerHTML += `${item.title} - ${item.desc} <hr>`
// })
// } catch (error) {
// console.log('error', error);
// }
// }
// Promise Then | POST REQUEST
// const makeRequest = () => {
// const init = {
// method: "POST",
// headers: {
// 'Content-Type': 'application/json'
// },
// body: '{"title": 10, "desc": 10}'
// }
// fetch("http://127.0.0.1:8000/student/", init)
// .then((res) => {
// if (!res.ok) {
// console.log(res.statusText);
// }
// console.log("res", res);
// return res.json();
// }).then((data) => {
// console.log(data);
// }).catch((err) => {
// console.log("error", err);
// });
// }
const makeRequest = async () => {
try {
const init = {
" method " : " PUT " ,
" headers " : {
" Content-Type " : " application/json "
},
" body " : ' {"title": 100, "desc": 100} '
}
const res = await fetch ( " http://127.0.0.1:8000/student/630e306ba6306216f4fde80a " , init );
if ( ! res . ok ) {
throw new Error ( res . statusText );
}
const data = await res . json ();
console . log ( data );
} catch ( error ) {
console . log ( " error " , error );
}
}
btn . addEventListener ( ' click ' , makeRequest );
Enter fullscreen mode
Exit fullscreen mode
Thank You.
You can follow us on:
Youtube
Instagram
Top comments (0)