script.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //Closures and scopes
  2. async function jsonPost(url, data) {
  3. let response = await fetch(url, {
  4. method: "POST",
  5. headers: {
  6. 'Content-Type': 'application/json'
  7. },
  8. body: JSON.stringify(data)
  9. });
  10. if (response.ok) {
  11. console.log('work')
  12. let json = await response.json();
  13. console.log(json)
  14. return json;
  15. } else {
  16. new Error('jsonPost failed'+ response.status);
  17. }
  18. }
  19. /* function jsonPost(url, data) {
  20. return new Promise((resolve, reject) => {
  21. var x = new XMLHttpRequest();
  22. x.onerror = () => reject(new Error('jsonPost failed'))
  23. //x.setRequestHeader('Content-Type', 'application/json');
  24. x.open("POST", url, true);
  25. x.send(JSON.stringify(data))
  26. x.onreadystatechange = () => {
  27. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  28. resolve(JSON.parse(x.responseText))
  29. } else if (x.status != 200) {
  30. reject(new Error('status is not 200'))
  31. }
  32. }
  33. })
  34. } */
  35. jsonPost('https://jsonplaceholder.typicode.com/posts', {func: 'addMessage', nick: "HellWords", message: 'AHHAAAH'}).then(res => console.log(res)
  36. )