ramkrushna
ramkrushna

Reputation: 27

How can resolve **Uncaught Reference Error: io is not defined at client.js:1:16** error?

I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like

Uncaught ReferenceError: io is not defined
    at client.js:1:16

and

GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)

plz help me to get out from this frustration. here are respective code:-

const express=require("express");

const http=require("http");

const app=express();

const server=http.createServer(app);

const io=require("socket.io")(server)

app.get("/",function (req,res) {
    res.sendFile(__dirname+"/index.html");
})

app.use(express.static(__dirname+"/public"))

io.on("connection",(socket)=> {
    console.log('Connected');

})

app.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
})

code at client.js:-

const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
    name = prompt("what do your friends call you?");
}while(!name);

textarea.addEventListener("keyup",function (e) {
    if(e.key==="Enter"){
        sendMessage(e.target.value);
    }
})

function sendMessage(message) {
    let msg={
        user:name,
        message:message
    }
    appendMessage(msg,"outgoing")
}

function appendMessage(msg,type) {
    let mainDiv=document.createElement("div")
    let className=type
    mainDiv.classList.add(className,"message")

    let markUp=`
    <h4>${msg.user}</h4>
    <p>${msg.message}</p>
    `
    mainDiv.innerHTML=markUp
    msgArea.appendChild(mainDiv)
}

It would be very helpful to me if you resolve this issue. Thank you in advance!!

Upvotes: 2

Views: 2807

Answers (3)

EdPic McGamson
EdPic McGamson

Reputation: 11

I had been fiddling around with this kind of problem for weeks. I was not able to solve this problem and it had been stressing me out. But Alas, I finally found the solution by searching in several sources. So I am going to tell the step by step process on how to fix it.

  1. First and foremost, install the socket.io package by doing in terminal (npm install socket.io)

  2. Second, type npm install nodemon

  3. Third, type npm init --yto get the file package.json. Then, in the package.json, at "scripts": {}, write "devStart": "nodemon server.js" (so you don't have to re-run the code in the server) and also "start": "node server.js". Then, at "main": , type "main": "server.js"

  4. Now, in your script.js, you forgot to put the link in io() as an argument. For instance, you can do:

     const socket = io('http://localhost:3000'); //You need to pass in the localhost:3000
     let name;
     let textarea=document.querySelector("#textarea");
     let msgArea=document.querySelector(".mssg_area");
     do{
         name = prompt("what do your friends call you?");
     }while(!name);
    

    This will tell the server to access the webpage in localhost:3000

  5. Then, in the server.js, import the module socket.io by doing:

     const express = require('express');
     const app = express();
     const server = require('http').Server(app);
     const io = require('socket.io')(server);
    

which you did correctly.

But, in the last part of your code, you should do:

    server.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
    })

instead of: app.listen()

  1. Now, this is the most confusing part. This is where the error kicks in. The reason why we get the Error:

     Uncaught ReferenceError: io is not defined
     at client.js:1:16
    

    is because we haven't imported/require the module for the socket.io in the client.js. In order to do that, we first need to get the module from the node_modules folder. So:

  • Scroll and Find the socket.io module in the node_modules folder in VSCode ( you should see socket.io in it)

  • Make a new folder in your directory/folder that has your client.js and server.js called public

  • Then copy or move the file/module to the new folder public

  • Now, go to your HTML file and in the <body> type the following:

      <body>
      <script src="public/socket.io/client-dist/socket.io.js"></script>
      <script src="client.js"></script>
      </body>
    

    Now, I might be wrong here since people do the other way that is(Doesn't work for me and probably you):

      <script src="http://localhost:3000/socket.io/socket.io.js"></script>
      <script src="client.js"></script>
    

    which, in my case, doesn't work for me because there is no such socket.io module in localhost/website. But, it probably doesn't work for me since I am using windows. So, if the first <script> tag I gave you didn't work, then you can try this one.

The point what I'm trying to tell you is, you need to import/require the socket.io module for the client.js in order for it to work. Otherwise, it will give that Unreferenced Error. Doing const io = require("socket.io") in client-side javascript won't work. You have to import it using <script> tag in the body. Or by doing <script defer src="..."> in the head.

So after all of this, it should work. Go to your server.js and run the server at localhost:3000. Go to Chrome(or other sites) and type localhost:3000

If the error is still there, then maybe the path to your public folder with the socket.io module is wrong OR I am wrong.

If you get the CORS error:

    const io = require('socket.io')(server, {
    cors: {
      origin, "*" //Or type your localhost or link
      methods: ["GET", "POST"]
    }
    }); 

you can go to info on socket.io Cors for more info.

Or install the cors module by doing npm install cors

Apologies if I did something wrong or for my broken English. I am terribly sorry as this is my first ever StackOverFlow answer and I couldn't just let this question go to rest. I must answer as I have the viable solution for it. So Thanks for reading this.

Upvotes: 1

farhad
farhad

Reputation: 226

on the client side you should install socket.io-client not socket.io

Client Api

Upvotes: 1

Isha
Isha

Reputation: 161

Be sure, you have installed socket.io module. If not installed, install this by using command - npm install socket.io

Upvotes: 0

Related Questions