Im very new to servers and node js and js but I am trying to construct a dynamic web page. On this webpage I have a comment form where people can leave a comment. My problem is that on the server-side this comment form works fine but I am trying to implement some client-side js so that when they submit a form if an error occurred (e.g. not all fields were filled) or if no error occurred an alert appears on the webpage saying an appropriate message for either case. I also want the form to clear after the submit button has been pressed and the details have been saved to the server if there was no error. Currently the form resets before the details save to the server so in the server all the fields saved are blank and I get this error:
GET http://127.0.0.1:3000/comment 404 (Not Found)
handleFormSubmit @ main.js:43
this is my code : Index.html
<html>
<head>
</head>
<body>
<h1>Comment!</h1>
<form action='http://localhost:3000/comment' method='POST' id='CommentSection'>
<div class='form-group'>
<label for='username'>username</label>
<input class='form-control' name='username'>
</div>
<div class='form-group'>
<label for='Title'>Info</label>
<input class='form-control' name='title' >
</div>
<div class='form-group'>
<label for='Comment'>Comment</label>
<input class='form-control' name='comment' >
</div>
<button type='submit' class='btn btn-primary'>Submit</button>
</form>
<script src='client.js'></script>
</body>
</html>
server.js
let AllComments=[];
app.post('/comment', (req, res) => {
const com = req.body;
console.log(com);
AllComments.push(com);
res.status(201);
});
client.js
async function commentSubmit(event) {
fetch('http://127.0.0.1:8090/comment');
alert('success');
CommentSection.reset();
}
const CommentSection = document.getElementById("CommentSection");
commentForm.addEventListener("submit", commentSubmit);
You would need to add a .then()
method call to your handleFormSubmit
method, so:
fetch('http://127.0.0.1:3000/comment').then(() => {
alert('comment added');
})
fetch
returns a Promise
, and is an async
method call, so in your case, alert
is triggered after the fetch
call is made but not necessarily completed. The .then()
method is triggered once the Promise
is resolved, so in order to run code once this happens, you store it in the .then()
method.
Now in your specific use case, you want to handle successful calls and errored calls. But there is one other consideration - are you only using failed calls to determine whether a call is successful, or can the server's response signify an error? By default, fetch
doesn't convert the response to json
(assuming your data is being returned from the server as json
. . For this, you would need to do the following (assuming the server returns a success/fail response as well:
fetch('http://127.0.0.1:3000/comment').then((res) => {
return res.json();
}).then((res) => {
if (res === 'success') {
alert('comment added');
} else {
alert('An error has occurred when trying to add your comment');
}
}).catch((e) => {
alert('An error has occurred when trying to add your comment');
})
A few other points that I had missed originally, but from the conversation in the comment thread:
Since your API is exposed by the server as a POST
request, you need to add additional options to your fetch
request, changing the method to POST
, as well as adding the data that you want to send to the server. To do this, you can add the following:
let options = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
// where data is your form fields
body: JSON.stringify(data)
}
// Replace '...' with code from above or whatever functionality you
// need once Promise resolves
fetch('http://127.0.0.1:3000/comment', options).then(...)
For more on fetch
, check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
To get form data values, if there aren't too many, you can try this for each of the fields: let val = document.getElementById('someId').value
Lastly, the way your form is currently set up, once you hit submit, it will refresh by default. If you want to prevent that from happening, before the fetch
call, add event.preventDefault()
, where event
is the EventListener
that was triggered (your current method signature should be sufficient for this).
thank you so much! this fixed the fact that empty strings were being stored on the server. However I'm still getting the error I was getting before?
Thank you so much for all your help I've actually learnt so much about fetch just from this question !
Which error are you referring to?
main.js:43 GET http://127.0.0.1:3000/comment 404 (Not Found) handleFormSubmit @ main.js:43
This error always appears after I press the submit button eventhouh( before I added the suggested error handler) It would append to the array of comments and do whats its supposed to despite showing an error.Do you also have anyway of checking that all the fields are filled in the form?