使用节点获取数组仅从 api 中提取价格
Extract the price only from api using node-fetch array
对于一个基本问题,我很抱歉,我一直在尝试使用 node-fetch 从 API
中仅提取价格
const fetch = require('node-fetch');
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => console.log(text))
let AvgPrice = text.map(text => text.price);
我收到的错误是
internal/modules/cjs/loader.js:968
throw err;
^
非常感谢任何建议
您需要检查几件事情
- 关于 cjs/loader.js 的错误与您的代码本身几乎没有关系,而是与设置有关,例如您如何 运行 代码、文件命名等,
https://github.com/nodejs/help/issues/1846
- 此代码将return引用错误:文本未定义。
原因是您从未定义变量文本,然后尝试在其上调用映射函数。
此外,fetch 是一个异步函数,nodejs 是单线程非阻塞的。所以发生的事情是您向网站发送一个 http 请求(获取),这需要时间,但与此同时您的编码仍在 运行ning,因此继续您代码中的下一行。
让我们添加一些控制台日志
const fetch = require('node-fetch');
console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => {
console.log('2. I got my text', text)
})
console.log('3. Done')
您可能认为这会注销
- 开始吧
- 我收到短信 {"mins":5,"price":"0.4998"}
- 完成
不,它会注销
- 开始吧
- 完成
- 我收到短信 {"mins":5,"price":"0.4998"}
因为你获取了数据,然后你的程序继续,它退出了 3. 完成然后当它从 api.binance 获得数据时它退出了 2. 我收到了我的文本(注意关键字然后,稍后发生)
- map 是一个数组函数。 api returns 是一个对象。所以当你修复你的异步代码时,你会得到 TypeError text.map is not a function
由于它 return 是一个对象,您可以立即访问它 属性 text.price
对于一个基本问题,我很抱歉,我一直在尝试使用 node-fetch 从 API
中仅提取价格const fetch = require('node-fetch');
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => console.log(text))
let AvgPrice = text.map(text => text.price);
我收到的错误是
internal/modules/cjs/loader.js:968
throw err;
^
非常感谢任何建议
您需要检查几件事情
- 关于 cjs/loader.js 的错误与您的代码本身几乎没有关系,而是与设置有关,例如您如何 运行 代码、文件命名等,
- 此代码将return引用错误:文本未定义。
原因是您从未定义变量文本,然后尝试在其上调用映射函数。
此外,fetch 是一个异步函数,nodejs 是单线程非阻塞的。所以发生的事情是您向网站发送一个 http 请求(获取),这需要时间,但与此同时您的编码仍在 运行ning,因此继续您代码中的下一行。
让我们添加一些控制台日志
const fetch = require('node-fetch');
console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => {
console.log('2. I got my text', text)
})
console.log('3. Done')
您可能认为这会注销
- 开始吧
- 我收到短信 {"mins":5,"price":"0.4998"}
- 完成
不,它会注销
- 开始吧
- 完成
- 我收到短信 {"mins":5,"price":"0.4998"}
因为你获取了数据,然后你的程序继续,它退出了 3. 完成然后当它从 api.binance 获得数据时它退出了 2. 我收到了我的文本(注意关键字然后,稍后发生)
- map 是一个数组函数。 api returns 是一个对象。所以当你修复你的异步代码时,你会得到 TypeError text.map is not a function
由于它 return 是一个对象,您可以立即访问它 属性 text.price