I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet.
Interestingly, even though I followed a JavaScript tutorial and our codes were identical, the page did not refresh on the instructor's side but it does on mine.
class EasyHTTP {
async post(url,data){
const response = await fetch(url,{
method: 'POST',
headers:{'content-type':'application/json'},
body: JSON.stringify(data)
});
const resData = await response.json();
if(resData){
return resData;
}else{
await Promise.reject(new Error('ERROR: Dont Know'));
}
}
}
const http = new EasyHTTP();
// Submit POST
document.querySelector('.post-submit').addEventListener('click',submitPost);
function submitPost(e){
e.preventDefault();
//e.stopPropagation();
const title = document.querySelector('#title').value;
const body = document.querySelector('#body').value;
const data = {
title,
body
};
http.post('http://localhost:3000/posts',data)
.then(res => {
console.log(res);
})
.catch(err => console.log(err));
}
<input
type="text"
id="title"
class="form-control"
placeholder="Post Title"
/>
<textarea
id="body"
class="form-control"
placeholder="Post Body"
></textarea>
<button class="post-submit">Post It</button>
It's frustrating as I keep trying to resolve the issue with the page reloading each time I fetch a post. Any help would be greatly appreciated.