From 3942af77b498688e4e9c8d4bc891aa938d77c8ab Mon Sep 17 00:00:00 2001 From: Akif9748 Date: Thu, 11 Aug 2022 01:36:53 +0300 Subject: [PATCH] Better API communication --- public/js/request.js | 19 +++++++++++++++++++ public/js/send.js | 16 ++++------------ views/thread.ejs | 7 ++++--- 3 files changed, 27 insertions(+), 15 deletions(-) create mode 100644 public/js/request.js diff --git a/public/js/request.js b/public/js/request.js new file mode 100644 index 0000000..928e68d --- /dev/null +++ b/public/js/request.js @@ -0,0 +1,19 @@ +export default async function request(link, method = "POST", body={}) { + try { + const res = await fetch(link, { + method, + body: JSON.stringify(body), + headers: { + "Content-Type": "application/json" + } + }).then(res => res.json()) + + if (res.result.error) return alert(res.result.error); + + return res; + + } catch (err) { + alert(err); + } + +} \ No newline at end of file diff --git a/public/js/send.js b/public/js/send.js index 74c4e70..266d156 100644 --- a/public/js/send.js +++ b/public/js/send.js @@ -1,18 +1,13 @@ +import request from "./request.js"; + document.getElementById("send").addEventListener("submit", async e => { e.preventDefault(); const form = e.target; const data = new FormData(form); - fetch("/api/messages", { - method: 'POST', - body: JSON.stringify({ threadID: data.get("threadID"), content: data.get("content") }), - headers: { - "Content-Type": "application/json" - } - }).then(res => res.json()) + request("/api/messages", "POST", { threadID: data.get("threadID"), content: data.get("content") }) .then(res => { - if (res.result.error) return alert(res.result.error); - + if (!res) return; form.reset(); const message = res.result; document.getElementById("messages").innerHTML += `
@@ -37,8 +32,5 @@ document.getElementById("send").addEventListener("submit", async e => { `; - - }).catch(err => { - alert(err); }); }); diff --git a/views/thread.ejs b/views/thread.ejs index f21854a..95d3e2b 100644 --- a/views/thread.ejs +++ b/views/thread.ejs @@ -72,9 +72,10 @@ <% }); %> - + <% }%> <%- include("extra/footer") %>