2

I tried to fetch to get some data. I want to run in chrome browser.

When I try to fetch to reach out such data,I suffered error like

require is not defined

I found question below and I trying to usescript tag,

Client on node: Uncaught ReferenceError: require is not defined

But I couldn't find out what kind of file should be loaded.

If someone know scripttag solution, please let me know.

Thanks

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

var apikey="https://opentdb.com/api.php?amount=10";

fetch(apikey)
  .then(response => response.json())
  .then(json => {
    // console.log(json);
    console.log(json.results[0].question);
  });
Heisenberg
  • 4,787
  • 9
  • 47
  • 76

4 Answers4

2

You don´t need to import fetch, its part of JS.

var apikey="https://opentdb.com/api.php?amount=10";

fetch(apikey)
  .then(response => response.json())
  .then(json => {
    // console.log(json);
    console.log(json.results[0].question);
  });
Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40
0

Require is basically not defined,and it is a part of async function, give a read on this and make sure it is compatible with your version.

Arun Kumar
  • 355
  • 3
  • 10
0

fetch is supported by default at client side. You don’t need to require it and also require doesn’t work at client side without browserified js. You can remove the require statement.

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
0

Note that JavaScript runs in multiple environments. There are different module systems for each environment. Commonjs is the module system with require and module.exports, this is used in the node.js runtime. In the browser you won’t see support for commonjs. Instead you’ll see a few different approaches to loading code.

Read more about all of the different module systems in the JS ecosystem here https://tylermcginnis.com/javascript-modules-iifes-commonjs-esmodules/.

arete
  • 1,903
  • 4
  • 17
  • 23