I have been using express, mongoose, and JavaScript to build a single page application. Everything seems to be working fine, except for one thing - I do not want the form data to show up in the URL when making a post request. I attempted to use a redirect, but it seemed to cause an infinite loop.
Since this is a SPA, I am avoiding using the form method="post" as it would result in a page redirection. My goal is to avoid displaying or redirecting from the URL with query information.
http://localhost:2000/?firstName=John&lastName=James&age=40
This is the structure of the form (index.html) --
<form id="formId">
<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="text" name="age">
<button type="submit" onclick="processForm(event)">Save</button>
</form>
Below is the JavaScript code for handling the form :
function processForm(event){
var formData = new FormData(document.forms[0])
const queryString = Object.fromEntries(
Array.from(formData.keys()).map(key => [
key, formData.getAll(key).length > 1 ?
formData.getAll(key) : formData.get(key)]));
postData(queryString);
}
async function postData(data) {
fetch('/people', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response =>response.json())
.then(data => console.log('Success:', data))
.catch((error) => {
console.error('Error:', error);
});
};