Better API communication

This commit is contained in:
Akif9748 2022-08-11 01:36:53 +03:00
parent 56b55b042b
commit 3942af77b4
3 changed files with 27 additions and 15 deletions

19
public/js/request.js Normal file
View file

@ -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);
}
}

View file

@ -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 += `<br>
@ -37,8 +32,5 @@ document.getElementById("send").addEventListener("submit", async e => {
</div>
</div>`;
}).catch(err => {
alert(err);
});
});

View file

@ -72,8 +72,9 @@
<% }); %>
<script>
<script type="module">
import request from "../js/request.js";
document.addEventListener("click", async e=>{
if (!e.target.id.includes("like"))return;
@ -102,7 +103,7 @@
</form>
<% if (user){ %>
<script src="/js/send.js"></script>
<script type="module" src="/js/send.js"></script>
<% }%>
<%- include("extra/footer") %>