JS – ReferenceError: fetch is not defined

You’re running it on Node JS instance in Paiza.io. Use CodeSandbox or CodePen for running your code please. And here… Paiza runs on Node JS not on Browser.

In your example, you need to use fetch() this way:

fetch(
  "https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay"
)
  .then((res) => res.json())
  .then((obj) => document.write(obj["data"]["received_value"]));

 Run code snippetExpand snippet

Here’s the Code Sandbox: exciting-bhaskara-sksve


The fetch() API is a browser API implemented in the major browsers. If you are planning to use the same in the Node JS Runtime, then you have to make use of 3rd Party Fetch libraries like node-fetch.

Install node-fetch:

npm install node-fetch

Then include it in the code.

const fetch = require('node-fetch');

If you’re trying to access plain text, then use:

fetch('https://example.com/')
    .then(res => res.text())
    .then(body => console.log(body));

If you’re using JSON (your solution here), then use:

fetch('https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay')
    .then(res => res.json())
    .then(json => console.log(json));

Another alternative will be Axios, which is a Promise based HTTP client for the browser and node.js. You have an awesome Axios Cheat Sheet available for common uses.

Install axios:

npm install axios

Then include it in the code.

const axios = require('axios');

For your case, you can do:

axios.get('https://sochain.com/api/v2/address/LTC/LMSuo8W7CiXs8oFs1sJh77AQ54tCZM42Ay')
  .then(function (response) {
    console.log(response);
  });

Leave a Comment