首页 > 解决方案 > 节点 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);
});

标签: javascriptnode.js

解决方案


fetch 模块不使用 Promises,它使用传统的节点样式回调。您可以使用util.promisify对函数进行承诺:

const fetch = require("util").promisify(require("fetch").fetchUrl)

请注意,这个 fetch 模块已经有 4 年没有更新了。如果您想使用 Promise ,我建议使用更新的 fetch 模块,该模块支持诸如node-fetchgotrequest之类的 Promise。


推荐阅读