TypeError:无法读取未定义的属性“ then”-尝试使用纯JavaScript提取数据

时间:2019-07-12 09:19:24

标签: reactjs rest api sockets express

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

我想以前使用nodejs提取,但是无法识别提取功能,因此我之前没有进行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'

1 个答案:

答案 0 :(得分:0)

该帖子已按照@Bhawana的答案进行了更正:use const fetch = require(“ fetch”);仅代替const fetch = require(“ fetch”)。fetchUrl,否则您可以使用node-fetch包。

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