Submitting form data as JSON using Axios' POST method


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!

Answer №1

When faced with this scenario, you have two main options:

  1. One option is to utilize v-model for binding form inputs:
<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>

You can then use these values to construct a JSON object when sending data:

methods: {
    getPostsViaREST() {
      // Instead of form data, create a JSON object here
      var user = {
        // Ensure that 'name' and 'surname' are present in [data] or [computed]
        name: this.name,
        surname: this.surname
      };

      axios.post("/users", user)
        .then(response => {
            this.getViaREST()
        })
},
  1. Alternatively, you could retain your current code and modify the backend to accept form data: It's important to remember that client requests cannot enforce specific requirements on how the backend processes data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding javascript code to HTML using Express

Currently, I am in the process of building a web application utilizing the Express framework to create Impress.js presentations and implementing a visual editor for them. I have configured the app.js to only fetch the .html file, but my objective is to inc ...

Shrinking image when resizing view in three.js

I am currently working on developing an online 3D manipulation tool using THREE.js. The initial setup includes a rotating cube and grid within the view. The issue I am facing is that when I resize the browser window, the THREE.js screen does not adjust acc ...

The double click feature is not functioning properly when used in conjunction with the selectpicker Boostrap

<select class= "selectpicker" id="cus_id"> <option value="654" >test1</option> <option value="6877" >test2</option> <option value="8687" >test3</option> </select ...

Issue encountered while creating the bean named 'restHandlerMapping': The path mapping is missing. The bean 'repositoryController' needs to be mapped to a non-empty path

Need help with writing an API for authorization using JWT and CSRF, but encountering an error. Any suggestions on how to resolve this? Thanks in advance Error: An error occurred while creating a bean named 'restHandlerMapping' which is def ...

In the event that the name and operator match, the recent value will be updated, but this functionality does not apply during the second

My application involves an array of filters containing the name, operator, and value: [{name="pricing.price", op="gte", value=10000}, {name="pricing.price", op="gte", value=10000}] After applying these filters and refreshing the page, the last set of fil ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

Using ReactJS to Apply Map and Filter Functions to JSON Data via Props

Struggling with a perplexing issue that seems trivial. Can't seem to find the right solution... I've got a db.json file structured like this: { "applicants": [{ "id": 1, "firstName": "John", "lastName": "Doe", "email": "& ...

Unable to retrieve the error message from the error object

In my express app, I have the following line of code: catch (err) { res.status(500).send(err.message); } Upon logging the error, I am presented with this message: name: 'TokenExpiredError', message: 'jwt expired', How ...

Strategies for updating the 'prevState' variable in React.js

I've encountered an array of objects that I need to update the state for. Toggling between the first and second items in the array, the value of isTrue changes from false to true. However, I want the first item to have isTrue: true, and only when I cl ...

Update pinpoint descriptions in JavaScript using the Google Maps API

I found this JS code on a website called GeoCodeZip After setting up the code on my server at this link, I realized the possibilities for customization. You can check out the source code to see how it works. Here's an image of the system: https://i. ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

What is the best way to offer compressed files on a webpage for easy extraction by a function and integration with a library?

In the process of creating an application using threejs, I have made sure to optimize my 3D models effectively. However, even after this optimization, the total size of all the models combined still amounts to a significant number like 100-150 Mb without i ...

Issue with pandas DataFrame json data conversion/extraction loop not functioning as expected

Currently, I am in the process of following an EDA walkthrough where I aim to convert/extract JSON data within a dataframe using a loop to handle columns containing JSON data. To achieve this, I have established a list for the loop to iterate through and s ...

Spring MVC controller not respecting the "consumes" attribute

The following controller is what I have: @RestController @RequestMapping(value = "/v1/mail", consumes = {APPLICATION_JSON_VALUE}) @ResponseStatus(OK) public class MailController { private CoreOutRestAdapter coreAdapter; @Autowired public Mai ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...

In ReactJS, one can create a variable and include a map function by first declaring the variable and then using the map function within the component. If you

Having trouble integrating the accordian.js page into the app.js main page for compilation. Need help defining and writing out the function correctly, any suggestions? Below is my code: App.js: How do I incorporate the components from the accordian.js pa ...

Is there a more efficient method to display and conceal multiple div elements with jQuery?

I am looking for an alternative method to use jQuery to show and hide divs. This code is specifically for testing purposes and includes a large number of divs that will make the code quite long once all are added. HTML Code <!DOCTYPE html> <html ...

JavaScript code for AES encryption that is compatible with PHP's mcrypt module

Challenge I am faced with the task of encrypting data using Javascript and decrypting it in PHP. I have decided to use Mcrypt in PHP with the AES encryption method, but I am struggling to find a suitable decryption algorithm in Javascript that is compatib ...

What could be the reason for JavaScript delaying the execution of DOM statements until a variable is true?

Today I've been tackling numerous bugs, but there's one particularly tricky bug that has me stumped. The snippet of code below pertains to a basic logon page. Currently, the only valid username is 'admin' and the corresponding password ...

When JSON is printed using console.log in Node.js, it is displayed in a format

Is there a way to format JSON in a similar style to how Node.js does it? I'm looking for a standard module or method that allows me to print JSON with spacing between keys, new lines when necessary, and potentially even color coding. https://i.sstati ...