[英]How to fix Uncaught ReferenceError: require is not defined
I tried to fetch
to get some data.我试图
fetch
一些数据。 I want to run in chrome
browser.我想在
chrome
浏览器中运行。
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 use script
tag,我在下面发现了问题,我尝试使用
script
标签,
Client on node: Uncaught ReferenceError: require is not defined 节点上的客户端:未捕获的 ReferenceError:未定义要求
But I couldn't find out what kind of file should be loaded.但我找不到应该加载什么样的文件。
If someone know script
tag solution, please let me know.如果有人知道
script
标签解决方案,请告诉我。
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); });
You don´t need to import fetch, its part of JS.您不需要导入 fetch,它是 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); });
fetch is supported by default at client side.客户端默认支持 fetch。 You don't need to require it and also require doesn't work at client side without browserified js.
您不需要它,并且如果没有浏览器化的 js,您也不需要在客户端工作。 You can remove the require statement.
您可以删除 require 语句。
Note that JavaScript runs in multiple environments.请注意,JavaScript 在多个环境中运行。 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.
Commonjs 是带有 require 和 module.exports 的模块系统,在 node.js 运行时中使用。 In the browser you won't see support for commonjs.
在浏览器中,您不会看到对 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/ .在此处阅读有关 JS 生态系统中所有不同模块系统的更多信息https://tylermcginnis.com/javascript-modules-iifes-commonjs-esmodules/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.