Vue.js fetch返回空的responseText

问题描述 投票:-1回答:1

我想让我的第一个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未定义。如果我在浏览器中打开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个回答
2
投票

Response产生的fetch()没有responseText属性,因此undefined。您可以使用响应上的方法json()从响应中提取JSON数据。 responseTextXMLHttpRequest存在,但不与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));

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.