GalinaKG

GET - POST - PATCH - DELETE -> Helper

Mar 29th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // method -> "GET"
  2. function Event_GET_Function() {
  3.     fetch(baseUrl)
  4.         .then((response) => response.json())
  5.         .then((infoFromServer) => {
  6.             for (let row in infoFromServer) {
  7.                 console.log(infoFromServer[row]);
  8.                 // pick data from array of objects for exmpl:
  9.                 let name = infoFromServer[row]['name'];
  10.                 let age = infoFromServer[row]['age'];
  11.                 let id = infoFromServer[row]['_id'];
  12.             }
  13.         });
  14. }
  15.  
  16.  
  17.  
  18. // method -> "POST"
  19. function EventPOST_Function() {
  20.     let dataObj = {
  21.         'student': student,
  22.         'age': age,
  23.     };
  24.     const headers = { method: 'POST', body: JSON.stringify(dataObj) };
  25.  
  26.     fetch(someUrl, headers)
  27.         .then(() => someFunc());
  28.  
  29. }
  30.  
  31.  
  32.  
  33. // method -> "PATCH"
  34. function EventUPDATE_Function(event) {
  35.     let id = event.target.parentNode.id; // Locate the "ID".
  36.     let patchUrl = baseUrl + `${id}`;
  37.     const headers = { method: 'PATCH', body: JSON.stringify({ name: newName }) };
  38.  
  39.     fetch(patchUrl, headers)
  40.         .then(() => someFunc());
  41. }
  42.  
  43.  
  44.  
  45. // method -> "DELETE"
  46. function EventDELETE_Function(event) {
  47.     let id = event.target.parentNode.id; // Locate the "ID".
  48.     let delUrl = baseUrl + `${id}`;
  49.     const headers = { method: 'DELETE', };
  50.  
  51.     fetch(delUrl, headers)
  52.         .then(() => someFunc());
  53. }
Add Comment
Please, Sign In to add comment