Javascript Vue.js fetch返回空的responseText
我正在尝试让我的第一个vue.js应用程序正常工作。至少我能够使用以下代码对结果200执行“获取”(这是某种成功):Javascript Vue.js fetch返回空的responseText,javascript,vue.js,fetch-api,Javascript,Vue.js,Fetch Api,我正在尝试让我的第一个vue.js应用程序正常工作。至少我能够使用以下代码对结果200执行“获取”(这是某种成功): fetch("validate-recaptcha.php", { method: "post", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, /
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处于未定义状态。如果在浏览器中打开,我会得到以下信息:
{"secret":"yoursecretkey","remoteip":"97.33.22.522"}
因此,至少内容不是空的,但是JavaScript显示消息“OK undefined”
链接:
fetch()
没有responseText
属性,因此未定义。您可以使用响应上的方法JSON()
从响应中提取JSON数据。与XMLHttpRequest
一起存在,但不与fetch()
一起存在:
希望这有帮助 使用response.json()我得到[object Promise]是什么意思?如何将其转换为文本?要提取正文,这是一个可读的流,需要针对响应执行json()
和text()
。这些方法返回承诺,需要使用then()
访问内部内容。在最基本的级别response.json()。然后(data=>console.log(data))代码>。在获取后的第一次then()
中,您将无法直接访问正文的内容。您需要执行这些方法之一,并使用附加的then()
。谢谢
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));