I'm trying to post data from an HTML form to a REST backend service which consumes JSON as data.
Having defined my form:
<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'm using to POST data:
methods: {
getPostsViaREST: function() {
var form = document.querySelector('form');
var user = new FormData(form);
axios.post("/users", user)
.then(response => {
this.getViaREST()
})
},
However I get a 415 error response, so I guess the problem is that I'm not sending data as JSON (the backend consumes JSON). I guess a workaround could be using a document.getElementById and post the single fields. For the sake of learning, I wonder if that's still possible to do it using FormData.
Edit: I've tried some approaches to transform the form data to JSON but it seems an empty payload is 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()
})
},
Thanks!