【问题标题】:I am trying to connect to an API using WebSocket but I got this Uncaught ReferenceError: require is not defined我正在尝试使用 WebSocket 连接到 API,但我得到了这个 Uncaught ReferenceError: require is not defined
【发布时间】:2022-12-11 17:31:08
【问题描述】:

Installation of the api on gitHub


    const WebSocket = require("ws");
    const DerivAPI = require("@deriv/deriv-api/dist/DerivAPI");

    // app_id 1089 is for testing, create your own app_id and use it here.
    // go to api.deriv.com to register your own app.
    const connection = new WebSocket(
    "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    );
    const api = new DerivAPI({ connection });
    const basic = api.basic;

    basic.ping().then(console.log);

但我得到 ReferenceError: require is not defined

【问题讨论】:

  • 您正在从 Node 上的 CommonJS 模块中进行尝试,对吗?

标签: javascript api npm websocket


【解决方案1】:

要解决 "ReferenceError require is not defined" 错误,请删除 package.json 文件中设置为 module 的类型属性,并将所有具有 .mjs 扩展名的文件重命名为具有 .js 扩展名。

包.json

{
  // ?️ this should be removed if you want to use `require`
  "type": "module",
  // ... ?️ rest
}

或者,您可以使用带有 importexport 关键字的 ES6 模块语法。

如果要使用导入/导出语法导入和导出模块,请在 package.json 文件中将类型属性设置为 module

包.json

{
  // ?️ add this
  "type": "module",
  // ... ?️ rest
}

您必须将 require 和 module.exports 语法替换为 import 和 export 关键字。

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2013-08-14
    • 2017-02-25
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多