Axios. How do I send data via Post?

There is such a code:

data () {
    return {
      loading_cell_phone_number: '',
      loading_zip_code: '',
      loading_city: '',
      loading_street: '',
      loading_house_number: '',
      loading_company_name: '',
      loading_first_name: '',
      loading_surname: '',
    }
  },

methods: {

     sendTrackerClientData: function () {
      axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=", this.$store.state.tracking_data.key_id+
        {data2: 1 }
        , {
           params: {
             user_key_id: this.$store.state.localStorage.userKeyId,
           },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        .then(response => {
      
        })
        .catch(function (error) {
          console.log(error);
        });
    },

  },

In this example, you can observe an attempt to send data(pay attention to the parameter '{data2: 1 }') to the server - via a Post request.


Instead of using the specified parameter to send data in the form of a key-value-in my case, the following is sent:

enter a description of the image here


Questions:

1) Why do I pass an empty string as a value, and the key along with the value as a parameter?

2) Is it possible in this case to somehow send data via post in such a way that the key would be the value: 'data2'
and the value of this key would be `1 ' and without any empty strings?

Author: Mike Kharkov, 2020-07-30

3 answers

Use the following parameters to configure Axios

axios({
 url: '...',
 params: {...},
 data: {...} 
})

Url - The URL to which the request will be made

Params - URL parameters to be sent with the request

Data - data to be sent as the request body. Applies only to query methodsPUT, POST, DELETE , and PATCH. When transformRequest is not set, it must be one of the following types:

// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer

PAY ATTENTION TO DATA, THE TYPE OF WHICH DEPENDS ON THE HEADERS THAT YOU WILL PASS

Headers - headers for the request

Here is an example:

For "Content-type": "application/json; charset=UTF-8"

const app = new Vue({
  el: "#app",
  data: {},
  mounted() {
    this.postRequest()
  },
  methods: {
    postRequest() {
      axios({
          method: 'post',
          url: 'https://jsonplaceholder.typicode.com/posts',
          params: {
            user_key_id: 'USER_KEY_ID',
          },
          data: {
            title: 'new_title',
            body: 'new_body',
            userId: 'userid'
          },
          headers: {
            "Content-type": "application/json; charset=UTF-8"
          }
        })
        .then(function(response) {
          console.log('Ответ сервера успешно получен!');
          console.log(response.data);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app"></div>

And for application/x-www-form-urlencoded

enter a description of the image here

For application/x-www-form-urlencoded: values are encoded in tuples with a key, separated by the ' & 'character, with' = ' between the key and the value. I.e., for application/x-www-form-urlencoded, a format string must be passed to data :

data2=1&data3=2

More details you can read the link XMLHttpRequest POST, forms and encoding

I give an example below:

const app = new Vue({
  el: "#app",
  data: {},
  mounted() {
    this.postRequest()
  },
  methods: {
    postRequest() {
      axios({
          method: 'post',
          url: 'https://jsonplaceholder.typicode.com/posts',
          params: {
            user_key_id: 'USER_KEY_ID',
            action: 'tracking.data_save',
            key_id: 'KEY_ID'
          },
          data: `data2=${encodeURIComponent('1')}`,
          headers: {
            "Content-type": "application/x-www-form-urlencoded"
          }
        })
        .then(function(response) {
          console.log('Ответ сервера успешно получен!');
          console.log(response.data);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app"></div>
 1
Author: Mikalai Parakhnevich, 2020-07-31 12:28:55
    axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=" + this.$store.state.tracking_data.key_id, {
         data2: 1,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

Try this: the server should receive data2 = 1

 0
Author: Enokin, 2020-07-30 09:20:42

You can send it like this:

            axios({
                method: 'POST',
                url: 'https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=' + this.$store.state.tracking_data.key_id,
                params: { data2: 1 }
            }).then((response) => {
                console.log(response.data);
            })

enter a description of the image here

Or just move data2: 1 to params, if I understood

data () {
    return {
      loading_cell_phone_number: '',
      loading_zip_code: '',
      loading_city: '',
      loading_street: '',
      loading_house_number: '',
      loading_company_name: '',
      loading_first_name: '',
      loading_surname: '',
    }
  },

methods: {

     sendTrackerClientData: function () {
      axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=", this.$store.state.tracking_data.key_id+, {
           params: {
             user_key_id: this.$store.state.localStorage.userKeyId,
             data2: 1
           },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        .then(response => {
      
        })
        .catch(function (error) {
          console.log(error);
        });
    },

  },
 0
Author: nicolaa, 2020-07-30 09:27:15