mirror of
https://github.com/Akif9748/akf-forum.git
synced 2024-12-22 23:59:08 +03:00
Better API communication
This commit is contained in:
parent
56b55b042b
commit
3942af77b4
3 changed files with 27 additions and 15 deletions
19
public/js/request.js
Normal file
19
public/js/request.js
Normal 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -72,9 +72,10 @@
|
|||
|
||||
<% }); %>
|
||||
|
||||
<script>
|
||||
<script type="module">
|
||||
|
||||
|
||||
import request from "../js/request.js";
|
||||
|
||||
document.addEventListener("click", async e=>{
|
||||
if (!e.target.id.includes("like"))return;
|
||||
const res = await fetch("/api/messages/"+e.target.value+"/react/" + e.target.id, { method: 'POST' })
|
||||
|
@ -102,7 +103,7 @@
|
|||
|
||||
</form>
|
||||
<% if (user){ %>
|
||||
<script src="/js/send.js"></script>
|
||||
<script type="module" src="/js/send.js"></script>
|
||||
<% }%>
|
||||
|
||||
<%- include("extra/footer") %>
|
||||
|
|
Loading…
Reference in a new issue