我应该如何将代码从 XHR 转换为 Vue-Resource?

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

我想将 XHR 中的代码转换为 Vue-Resource 请求。

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);

这是我在 Vue-Resource 中的代码,但出现错误:

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);
      });

我不确定我的 vue 代码有什么问题。我需要在 body 参数中传递 channel?default

您可以将 data 作为 second 参数传递给 .post 方法。

必须是JSON格式。

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