Heisenberg
Heisenberg

Reputation: 5299

How to fix Uncaught ReferenceError: require is not defined

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);
  });

Upvotes: 2

Views: 4460

Answers (4)

arete
arete

Reputation: 1933

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/.

Upvotes: 0

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

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.

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 355

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.

Upvotes: 0

Hans Felix Ramos
Hans Felix Ramos

Reputation: 4434

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);
  });

Upvotes: 2

Related Questions