-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate.js
38 lines (34 loc) · 911 Bytes
/
create.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const form = document.getElementById("blogForm");
const formStatus = document.getElementById("form-status");
const sendBlog = async (e) => {
try {
e.preventDefault();
const author = form.author.value;
const title = form.title.value;
const body = form.body.value;
if (!author || !title || !body) {
throw "Please fill all the fields.";
}
const blog = {
author,
title,
body,
};
const res = await fetch("http://localhost:6500/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(blog),
});
const blogs = await res.json();
if (blogs) {
window.location.replace("./index.html");
} else {
throw "Blog not submitted.";
}
} catch (err) {
formStatus.innerText = err.name ? err.message : err;
}
};
form.addEventListener("submit", sendBlog);