stage6.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // изначальный вариант решения с async/await fetch - сам не знаю зачем сделал)
  2. /*const jsonPost = async (url, data) => {
  3. try {
  4. const response = await fetch(url, {
  5. method: 'POST',
  6. body: JSON.stringify(data)
  7. });
  8. if (!response.ok) {
  9. new Error(`An error has occurred: ${response.status}`);
  10. } else {
  11. return JSON.parse(await response.text());
  12. }
  13. } catch (e) {
  14. return e;
  15. }
  16. }
  17. const url = "http://students.a-level.com.ua:10012";
  18. sendButton.addEventListener('click', async () => {
  19. let nickValue = nickInput.value;
  20. let messageValue = messageInput.value;
  21. const newPost = await jsonPost(url, {
  22. func: 'addMessage',
  23. nick: nickValue,
  24. message: messageValue
  25. }
  26. );
  27. console.log(newPost.nextMessageId);
  28. });*/
  29. const jsonPost = (url, data) => {
  30. return fetch(url, {
  31. method: 'POST',
  32. body: JSON.stringify(data)
  33. }).then(response => {
  34. if (response.ok) {
  35. return response.json();
  36. } else {
  37. throw new Error(`An error has occurred: ${response.status}`);
  38. }
  39. }).catch(err => {
  40. console.log(err);
  41. });
  42. }
  43. const url = "http://students.a-level.com.ua:10012";
  44. sendButton.addEventListener('click', () => {
  45. let nickValue = nickInput.value;
  46. let messageValue = messageInput.value;
  47. const newPost = jsonPost(url, {
  48. func: 'addMessage',
  49. nick: nickValue,
  50. message: messageValue
  51. }
  52. );
  53. newPost.then(data => console.log(data.nextMessageId))
  54. });