javascript - 节点 js 中的 fetch 给出 TypeError: Cannot read property 'then' of undefined
问题描述
节点 js 中的简单 fetch 给出错误TypeError: Cannot read property 'then' of undefined,我在这里经历了很多答案,到处都提到要返回 Promise,但在这种情况下,返回的 Promise 对象立即与 then() 链接,下面是代码。
const fetch = require("fetch").fetchUrl
fetch('http://example.com/movies.json').then((response) => {
console.log(response);
});
解决方案
fetch 模块不使用 Promises,它使用传统的节点样式回调。您可以使用util.promisify对函数进行承诺:
const fetch = require("util").promisify(require("fetch").fetchUrl)
请注意,这个 fetch 模块已经有 4 年没有更新了。如果您想使用 Promise ,我建议使用更新的 fetch 模块,该模块支持诸如node-fetch、got或request之类的 Promise。
推荐阅读
- excel - Power Query 合并具有不同值的两列
- runtime-error - 行人代理的无法到达目标错误
- azure-devops-self-hosted-agent - 自托管代理不会自动更新
- visual-c++ - TVM_INSERTITEM 返回一个使用时会导致异常的 HTREEITEM
- python - requests.post 返回 {'code': 400, 'message': '必须在数据字段中提供 CSV 文件'}
- azure-functions - Azure 函数未向服务总线发送消息
- javascript - 我希望创建的 h3 每个都包含一个不同的句子,但是如果您单击相同的 h3 它应该给出相同的句子(当然是每页加载
- python - 在 unittest python 中使用模拟模块编写好的测试
- javascript - 如何在单个工作线程中监视对 SharedArrayBuffer 的更改?
- deployment - 部署到 Vercel 时如何包含配置文件