使用 Nodejs 提供网页,我几乎从在线示例中逐字复制了示例代码。在 chrome 调试器日志控制台中我收到消息: (索引):83 未捕获(承诺中)类型错误:无法读取未定义的属性(读取“json”)
我是第一次尝试“获取”操作,所以我可能会丢失一些东西。我在网上找不到任何关于为什么会发生这种情况的提及。我做了 npm install json 但这没有帮助。我发现没有任何内容提到应该安装或以其他方式包含的其他内容。
下面是我的代码,错误标记在包含“resoinse.json()”的行上
<script>
const {fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [ resource, config ] = args;
console.log("resource: " + resource);
console.log("config: " + config);
const response = await(resource, config);
console.log(" -- got response!");
}
fetch("/form-1.html", { method: 'POST'})
.then ((response) => response.json())
.then((json) => console.log(json));
</script>
提前致谢。
此函数不返回任何内容:
window.fetch = async (...args) => {
let [ resource, config ] = args;
console.log("resource: " + resource);
console.log("config: " + config);
const response = await(resource, config);
console.log(" -- got response!");
}
因此附加到结果
.then()
的任何 Promise
都不会收到值。您可以return
获得您期望的值:
window.fetch = async (...args) => {
let [ resource, config ] = args;
console.log("resource: " + resource);
console.log("config: " + config);
const response = await(resource, config);
console.log(" -- got response!");
return response; // <--- here
}
此外,我根本不明白这是如何工作的:
await(resource, config)
你肯定是这个意思吗?:
await originalFetch(resource, config)
说实话,我很惊讶前者没有给你错误。