I am facing an issue while trying to send data from an HTML form to a REST backend service that only accepts JSON. After setting up my form as follows:
<form name="form" >
<input type="text" placeholder="Name" value="name" size="60"/></div>
<input type="text" placeholder="Surname" value="surname" size="60"/></div>
<input type="submit" value="Save" @click="getPostsViaREST"/>
</form>
Here is the Axios method I have implemented for POSTing the data:
methods: {
getPostsViaREST: function() {
var form = document.querySelector('form');
var user = new FormData(form);
axios.post("/users", user)
.then(response => {
this.getViaREST()
})
},
Unfortunately, I received a 415 error response which indicates that I am not sending the data in JSON format (required by the backend). One potential solution could be manually extracting each field using document.getElementById and then posting them individually. However, out of curiosity, I would like to know if there's still a way to achieve this using FormData.
Edit: I made attempts to convert the form data into JSON but it appears that an empty payload is being sent to the server-side:
var form = document.querySelector('form');
var formData = new FormData(form);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
axios.post("/users", json)
.then(response => {
this.getViaREST()
})
},
Any suggestions or insights are greatly appreciated. Thank you!