【问题标题】:ReferenceError: Cannot access 'ws' before initializationReferenceError:在初始化之前无法访问“ws”
【发布时间】:2021-09-10 17:11:32
【问题描述】:

我正在尝试设置 ws,但我收到此错误:“未捕获的 ReferenceError:未定义要求”和“未捕获的 ReferenceError:在初始化之前无法访问 'ws'”。 我使用 node.js。这是代码:

const WebSocket = require('ws');

const serverAddress = "ws://127.0.0.1:5000";

const ws = new WebSocket(serverAddress);

function send_data(){
  ws.send(document.getElementById("message-input").value);
}

这是html代码:

<input class="input_color" type="text" id="message-input" value="type-here">
<button><input type="image" src="../../img/icon_send.png"id="send-button" alt="submit" 
class="send_button" onclick="send_data() "></button>
<script type="text/javascript" src="../../client.js">

【问题讨论】:

  • 您的意思是标签中的javascriptnodejs?如果 javascriptrequire() 在 js 中不存在。它是 Nodejs 的一部分
  • 你是在终端中通过node filename.js 运行它还是只是在浏览器中打开这个文件?
  • @ciekals11 我使用 git bash 运行它
  • 您发布的第一部分代码在client.js 文件中。我说的对吗?
  • @ciekals11 是的。

标签: javascript html node.js websocket ws


【解决方案1】:

您正在浏览器中使用 nodejs 代码。浏览器不知道“require”,所以你的代码永远不会像这样工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-09-30
    相关资源
    最近更新 更多