Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IO Is Not Defined – Socket.io

I’m currently working on a real-time chat web page. I was originally thinking about using PHP, but am testing out socket.io for the backend.

I’m running into a problem where the browser’s console logs Uncaught ReferenceError: io is not defined. I’ve looked this up many times on this site, as well as others, and most of the answers say to make sure that your <script> tag has the src pointing to http://localhost:3000/socket.io/socket.io.js and not just /socket.io/socket.io.js. I already have this in my HTML code. Here’s a snippet of the code:

index.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html lang="en-us">

<head>
  <title>Chat</title>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="../libs/jquery.js"></script>
  <script src="../libs/fontawesome.js" crossorigin="anonymous"></script>
  <script defer src="http://localhost:3000/socket.io/socket.io.js"></script>
</head>

<body>
  <!-- My code here -->

  <script type="text/javascript" src="script.js"></script>
</body>

</html>

script.js

const socket = io("http://localhost:3000");

socket.on("chat-message", (data) => {
  console.log(data);
});

server.js

const io = require("socket.io")(3000);

io.on("connection", (socket) => {
  socket.emit("chat-message", "Hello World!");
});

Basically, all it should do now is that when a user connects to the page, the server sends a request to the client with the data of Hello World!. The client then just console.log() this data.

I’m getting the Uncaught ReferenceError: io is not defined error in the BROWSER console, and it says the issue is in script.js in the first line: const socket = io("http://localhost:3000");.

Thank you in advance. Any and all help is appreciated.

>Solution :

The socket.io <script> tag has a defer attribute, meaning it will run after the document has been parsed. This means that it runs after script.js, which is not deferred. To fix this, just add a defer attribute to the script.js <script> tag, as deferred scripts run in the order they are defined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading