【问题标题】:How should I transform code from XHR to Vue-Resource?我应该如何将代码从 XHR 转换为 Vue-Resource?
【发布时间】:2019-01-14 08:32:12
【问题描述】:

我想将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

【问题讨论】:

    标签: vue.js xmlhttprequest vue-resource


    【解决方案1】:

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

    【讨论】:

    • 现在还不行,我大概再过5分钟就可以了。
    • 当然,没问题! :)
    • 如果我想传递一些参数?在headers 对象下传递一个对象是否正确? { data: { property: 'test', id: 1 } } ?
    • 什么样的参数?
    • 一个是数字,一个是字符串,只是一些数据
    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 2021-04-20
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2021-10-29
    相关资源
    最近更新 更多