Sajid Latif
Sajid Latif

Reputation: 119

How to pass an object to axios.post to handle the request in Vue Component?

I'm trying to pass an object through an axios.post. But apparently, the way I'm doing it is wrong. I'm getting this error

Error: "Request failed with status code 500"

When I send the data as a normal string I do not have any issues.

My axios.post code looks like this

axios.post('/api/send', {
  contactInfo: this.contactInfo
  })
    .then(function (response) {
     console.log(response.data);
     })
     .catch(function (error) {
      console.log(error);
      });

My contactInfo object is like this...

export default {
        name: 'app',
        data() {
            return {

                contactInfo: {
                    email: '[email protected]',
                    mobile: '11112222'
                }

            }
        },

Upvotes: 0

Views: 2998

Answers (3)

The response code is 500 so i think the problem is about your server.

Upvotes: 0

Sajid Latif
Sajid Latif

Reputation: 119

The best way to pass your data is to use this.$data

axios.post('url', this.$data)
  .then(function (response) {
    console.log(response);
    })
     .catch(function (error) {
      console.log(error);
      });

Upvotes: 1

H3lltronik
H3lltronik

Reputation: 886

This is what I do when I use axios c:

Use FormData and add it data using the .set method like this:

// Declare the body
let formData = new FormData ()
// Add data to body
formData.set('name1', variable1)
formData.set('name2', variable2)
// Request
axios.post('url', formData).then(response => {
  // Do something
}).catch(error => {
  // Do something
})

Upvotes: 0

Related Questions