Home > OS >  How to return a JSON endpoint in Vue using axios
How to return a JSON endpoint in Vue using axios

Time:02-21

I'm creating a web application using VueJS, C# and Entity Framework, but there is a problem. I don't know how to return a JSON using Axios to backend. In this project I'm using dynamic forms based on JSON schema and what I'm trying to do is when the user has completed the required fields, once he clicks on the 'send' button, that generated JSON should be redirected to my database where it should parse into a table with it's values.

Here is the function that "should" return the completed JSON but no success

returnJSON(){
         axios
       .post('http://localhost/jsonSchema/email.json')
       .then(response => (this.info = response))
      }

I'm not allowed to share more code, but i can provide a link from where I took the JSON schema: https://github.com/koumoul-dev/vuetify-jsonschema-form. I've tried json server as well, but no success, because once I change those fields into objects, the schema is not working anymore.

I have two questions:

  1. How can I return a link that contains the resulted JSON?
  2. Should I look at this problem from another point of view? Is it better to parse JSON first in C# then send that data to database instead of sending just an endpoint to be parsed directly into a stored procedure?

CodePudding user response:

Basically, the json schema does not affect how you send data back to the backend server, it just enforces that the data (form data in this case) follows a certain structure. Therefor:

Simply look at your form v-model:

<v-jsf v-model="model" :schema="schema" :options="options" />

...which is model in this case. This variable holds your data. Now send it to the server in your submit method:

async returnJSON(){
  this.info = await this.$axios.post('<YOUR SERVER URL>', this.model).then(response => response.data)
}

Note that I changed your returnJSON method to use async/await syntax, which is far more understandable here and also made it use response.data aswell as called axios in the way I suspect you need to call it (depending on your setup).

  • Related