Home > front end >  IO Is Not Defined - Socket.io
IO Is Not Defined - Socket.io

Time:01-03

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

<!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.

CodePudding user response:

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.

  • Related