Search code examples
vue.jsxmlhttprequestvue-resource

How should I transform code from XHR to Vue-Resource?


I would like to transform the code in XHR to Vue-Resource request.

XHR:

var data = "channel=default";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "url");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");

xhr.send(data);

and here's my code in Vue-Resource but I get an error:

this.$http.post(
        'url',
        {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: 'channel=default'
        }
      ).then(response => {
          console.log(response.body);
      }, error => {
          console.error(error);
      });

I am not sure what's wrong with my vue code. I need to pass channel?default in body parameter.


Solution

  • You can pass the data as the second parameter to the .post method.

    It must be in JSON format.

    this.$http.post(
        'url',
        { channel: 'default'},
        {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }
    ).then(response => {
        console.log(response.body);
    }, error => {
        console.error(error);
    });