BenSmith
BenSmith

Reputation: 431

nodeJS: io is not defined error on frontend

When I run my nodejs app with nodemon on localhost, on the frontend-side, socket.io is not being displayed and if I put /socket.io/socket.io.js at the end of the url, no socket library is displayed. The error I get is as follows: Chrome Debug Error msg

I have set-up the socket.io on the server and client side of the code and have installed the packages.

Is this a declaration error of socket.io in the code, or a system error of socket.io? [I'm using localhost and Heroku]

EDIT: Changed the syntax error in index.html file and changed app.listen to server.listen.

New Chrome Error msg


server.js:

const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');

const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);

app.use(express.static(publicPath));

io.on('connection', (socket) => {
  console.log('New user connected');

  socket.on('disconnect', () => {
    console.log('User was disconnected');
  });
});

server.listen(port , () => {
  console.log(`Server is up on port ${port}`);
});

index.html(client-side):

<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">

</head>

<body>
  <p>Welcome to the chat app</p>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('connect', () => {
      console.log('Connected to server');
    });

    socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  </script>
</body>

package.json:

{
  "name": "chat-app",
  "version": "1.0.0",
  "description": "",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "engines": {
    "node": "8.8.1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "socket.io": "^2.0.4"
  }
}

Upvotes: 0

Views: 302

Answers (1)

Jimmy
Jimmy

Reputation: 2841

You have a typo in the html file. Replace this line :

<script> src="/socket.io/socket.io.js"></script>

With

<script src="/socket.io/socket.io.js"></script>

That what the "SyntaxError: unexpected end of input" reveals from your screenshot.

Upvotes: 1

Related Questions