繁体   English   中英

如何修复未捕获的 ReferenceError:未定义要求

[英]How to fix Uncaught ReferenceError: require is not defined

我试图fetch一些数据。 我想在chrome浏览器中运行。

当我尝试获取此类数据时,我遇到了类似的错误

require is not defined

我在下面发现了问题,我尝试使用script标签,

节点上的客户端:未捕获的 ReferenceError:未定义要求

但我找不到应该加载什么样的文件。

如果有人知道script标签解决方案,请告诉我。

谢谢

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

您不需要导入 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); });

Require 基本上没有定义,它是 async function 的一部分,请阅读内容并确保它与您的版本兼容。

客户端默认支持 fetch。 您不需要它,并且如果没有浏览器化的 js,您也不需要在客户端工作。 您可以删除 require 语句。

请注意,JavaScript 在多个环境中运行。 每种环境都有不同的模块系统。 Commonjs 是带有 require 和 module.exports 的模块系统,在 node.js 运行时中使用。 在浏览器中,您不会看到对 commonjs 的支持。 相反,您会看到几种不同的加载代码的方法。

在此处阅读有关 JS 生态系统中所有不同模块系统的更多信息https://tylermcginnis.com/javascript-modules-iifes-commonjs-esmodules/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM