【问题标题】:TypeError: Cannot read property 'then' of undefined - Trying to fetch data in pure javascriptTypeError:无法读取未定义的属性“then” - 尝试在纯 javascript 中获取数据
【发布时间】:2019-11-22 01:03:44
【问题描述】:

我正在尝试使用纯 JavaScript 从带有 socket.io 的套接字端点获取数据。现在的想法是在客户端和我的 localhost 中的 API 之间使用套接字服务器。

之前想用nodejs fetch,但是无法识别fetch函数,然后我之前取消了require("fetch").fetchUrl做"npm install fetch"。

const fetch = require("fetch").fetchUrl
const io = require('socket.io')();

fetch('http://localhost/')    
.then(response => response.json()) 
.then(responseJson=>console.log(responseJson))

const port = 3001
io.listen(port)
console.log('Server available at: http://localhost:', port)

TypeError: 无法读取未定义的属性“then”

【问题讨论】:

  • 使用 const fetch = require("fetch");仅代替 const fetch = require("fetch").fetchUrl 或者您可以使用 node-fetch 包
  • 感谢您的贡献。没有 .fetchUrl 我得到了另一个错误:TypeError: fetch is not a function。
  • 让我试试 node-fetch 包
  • @Bhawana,比你好多了。它有效!
  • 我的荣幸!!!

标签: reactjs rest api sockets express


【解决方案1】:

根据@Bhawana 的回答更正了帖子:use const fetch = require("fetch");仅代替 const fetch = require("fetch").fetchUrl 或者您可以使用 node-fetch 包。

这个问题的解决方案非常简单:将 const fetch = require("fetch") 替换为 const fetch = require('node-fetch')

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2014-11-29
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多