0

I am trying to set up ws but I am getting this error: "Uncaught ReferenceError: require is not defined" & "Uncaught ReferenceError: Cannot access 'ws' before initialization". I use node.js.This is the code:

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

this is the html code:

<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">
9
  • you meant javascript or nodejs in your tags? If javascript then require() doesn't exist in js. It is a part of Nodejs Commented Jun 28, 2021 at 11:40
  • Are you running it in terminal via node filename.js or just open this file in browser? Commented Jun 28, 2021 at 11:44
  • @ciekals11 i use git bash to run it Commented Jun 28, 2021 at 11:45
  • The first part of code that you posted is in client.js file. Am i correct? Commented Jun 28, 2021 at 11:46
  • @ciekals11 yes. Commented Jun 28, 2021 at 11:47

1 Answer 1

1

You are using nodejs code in the browser. The browser doesn’t know ‘require’, so your code will never work like this.

Sign up to request clarification or add additional context in comments.

Comments