首页 > 解决方案 > Vue.js fetch 返回空的 responseText

问题描述

我正在尝试使我的第一个 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 未定义。如果我在浏览器中打开我查询的 URL,我会得到:

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

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

链接:

  1. 完整的源代码。
  2. 现场演示(按发送表格按钮)。

标签: javascriptvue.jsfetch-api

解决方案


产生的响应fetch()没有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));

希望这会有所帮助!


推荐阅读