【问题标题】:Vue.js fetch returns empty responseTextVue.js fetch 返回空的 responseText
【发布时间】:2018-09-14 02:16:57
【问题描述】:

我正在尝试使我的第一个 vue.js 应用程序工作。至少我可以使用以下代码对结果 200 进行“获取”(这是某种成功):

    fetch("validate-recaptcha.php", {
        method: "post",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },

        //make sure to serialize your JSON body
        body: JSON.stringify({
            name: "myName",
            password: "myPassword"
        })
    })
    .then((response) => {
        //do something awesome that makes the world a better place
        if (response.status == 200) {
            alert(response.statusText + " " + response.responseText);
        }
        else {
            alert("Error: " + response.statusText);
        }
    });

但不清楚为什么 response.responseText 在 undefined 中。如果我在浏览器中打开the URL I query,我会得到:

{"secret":"yoursecretkey","remoteip":"97.33.22.522"}

所以至少内容不为空,但 JavaScript 显示消息“OK undefined”。

链接:

  1. Full source 代码。
  2. Live demo(按发送表单按钮)。

【问题讨论】:

    标签: javascript vue.js fetch-api


    【解决方案1】:

    fetch() 产生的Response 没有responseText 属性,因此是undefined。您可以使用响应上的方法 json() 从响应中提取 JSON 数据。 responseText 存在于XMLHttpRequest,但不存在于fetch()

    fetch("validate-recaptcha.php", {
        method: "post",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: "myName", password: "myPassword" })
    })
    .then((response) => {
        if (response.status == 200) {
            alert(response.statusText);
        }
        else {
            alert("Error: " + response.statusText);
        }
    
        /* returns a promise that can be utilized using `then() */        
        return response.json();
    
        // could also use then() here
        // return response.json().then(data => console.log(data));
    })
    .then(data => console.log(data));
    

    希望对您有所帮助!

    【讨论】:

    • 使用 response.json() 我得到 [object Promise] 是什么意思?怎么转成文字?
    • 提取正文,这是一个可读流,有methods,如json()text(),需要针对response执行。这些方法返回承诺,需要使用then() 来访问内部内容。在最基本的层面上response.json().then(data => console.log(data));。 fetch 后,您将无法直接访问第一个 then() 中的正文内容。您需要执行其中一种方法并使用额外的then()。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2017-11-27
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多