1


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!

Francesco Marchioni
  • 4,091
  • 1
  • 25
  • 40
  • You're really just needing to [convert the form to json](https://stackoverflow.com/questions/41431322/how-to-convert-formdatahtml5-object-to-json) to post it. – Ohgodwhy Dec 13 '19 at 08:11

1 Answers1

1

You apparently have two options ahead:

  1. You can use v-model for form input binding:
<form name="form" >
    <input type="text" placeholder="Name" v-model="name" size="60"/></div>
    <input type="text" placeholder="Surname" v-model="surname" size="60"/></div>
    <input type="submit" value="Save" @click="getPostsViaREST"/>
</form>

And you can use them to build a json object when sending data:

methods: {
    getPostsViaREST() {
      // No form data, but json here
      var user = {
        // name and surname should exist in [data] or [computed] section
        name: this.name,
        surname: this.surname
      };

      axios.post("/users", user)
        .then(response => {
            this.getViaREST()
        })
},
  1. Or you can keep your code and change the backend to accept form data: You cannot dictate the backend to accept certain types through a client request.
tony19
  • 125,647
  • 18
  • 229
  • 307
vahdet
  • 6,357
  • 9
  • 51
  • 106
  • 1
    Thanks I've tried with the first approach and it worked. No matter it does not use FormData- all I wanted was avoiding using document.getElementById when we are close to 2020. :-) – Francesco Marchioni Dec 13 '19 at 08:31