首页 > 解决方案 > 我应该如何将代码从 XHR 转换为 Vue-Resource?

问题描述

我想将代码转换XHRVue-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代码有什么问题。我需要传入channel?defaultbody参数。

标签: vue.jsxmlhttprequestvue-resource

解决方案


您可以将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);
});

推荐阅读