我试图使用javascript从sochain块链api中获取数据,但是当我运行代码时,会得到以下错误:
ReferenceError: fetch is not defined
at Object.<anonymous> (/workspace/Main.js:1:12)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
那么,我的问题是,我做错了什么,为什么fetch会出现这个错误?我的代码是:
var json = fetch('https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay');
var obj = JSON.parse(json);
document.write(obj["data"]["received_value"]);
发布于 2020-11-17 11:37:28
您正在Paiza.io中的Node实例上运行它。请使用CodeSandbox或CodePen运行您的代码。而这里..。Paiza运行在Node JS上,而不是在浏览器上。
在您的示例中,您需要以这种方式使用fetch()
:
fetch(
"https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay"
)
.then((res) => res.json())
.then((obj) => document.write(obj["data"]["received_value"]));
下面是代码沙箱:令人兴奋的-巴斯卡拉-斯奎夫
fetch()
API是在主要浏览器中实现的一个浏览器API。如果您计划在Node运行时中使用相同的代码,那么您必须使用第三方获取库(如node-fetch
)。
npm install node-fetch
然后将其包含在代码中。
const fetch = require('node-fetch');
如果您试图访问纯文本,请使用:
fetch('https://example.com/')
.then(res => res.text())
.then(body => console.log(body));
如果您正在使用JSON (您的解决方案在这里),那么使用:
fetch('https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay')
.then(res => res.json())
.then(json => console.log(json));
另一种选择是阿西克斯,它是一个面向浏览器和node.js的基于承诺的HTTP客户端。您有一个非常棒的Axios备忘单可供通用。
安装axios
npm install axios
然后将其包含在代码中。
const axios = require('axios');
就你的情况而言,你可以:
axios.get('https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay')
.then(function (response) {
console.log(response);
});
https://stackoverflow.com/questions/64874484
复制相似问题