M Rahi
M Rahi

Reputation: 73

Problem Posting json data to API using Axios in Vue JS

I am trying to create a Axios request where i will post json data. The format of the data will be

{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}

But it is posting as

{"data":{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}}

Here is my code snippet:

var data = {
              "qBody" : question,
              "qAnswer" : trueFalseAnswer,
              "qOptions" : qOptions,
              "qType" : questionCategory,
              "qClass" : className,
              "qSubject" : subjectName,
              "qChapter" : chapterName,
              "qCreatorid" : qCreatorid,
              "qCreatorrole" : qCreatorrole
            };

    const newData =  JSON.stringify(data)
    
     this.$axios.post("http://128.199.192.87:8081/api/v1/questions/add",{
                  newData
                },{
                  'Content-Type': "application/json"
                }).then((response)=>{
                  console.log(response)
                })

How can I make the format correct? Thanks in advance

Upvotes: 0

Views: 1237

Answers (1)

tao
tao

Reputation: 90013

What you are console.log()-ing is not what you're sending. It is the response that's getting back from the server. If you want to log what you're sending, use:

console.log(newData);

... just before making the POST request.

Most likely, you don't need to stringify the request.

What you're seeing in the console is the server response. According to the response-schema in their documentation, the server's response data is placed in the .data property of the response object.

So, apparently, the server sends back the same data. With most servers, this means no error has occurred.


In fewer words, you are not sending your data wrapped as { data: ... }. If you were, you would be getting back: { data: { data: ... } }

Upvotes: 2

Related Questions