【发布时间】: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