javascript - 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”。
链接:
解决方案
产生的响应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));
希望这会有所帮助!
推荐阅读
- reactjs - 当单击按钮作为 React 中的组件时,如何在按钮内添加活动加载器?
- r - 使用 tidyverse 中的“recode()”将一系列值重新编码为一个数字
- html - 为什么关键帧不平滑?
- python - 在 python/QGIS 中使用以编程方式创建的索引字符串查找?
- asp.net-core - 为什么 dotnet build 在运行 release 时不包含文件夹?
- reactjs - 强制 Typescript Map 键/值是某种类型
- python - 使用 .format() 语法的区域感知字符串格式化
- python-3.x - 如何在特定时间范围内获取字典或数据集?
- time - 如何根据输入设置中断
- java - 如果不打算保留该字段(@Transient 等),是否可以在 JPA 实体中拥有一个公共最终实例字段?