0

I am going through the example listed below:

https://socket.io/get-started/chat/

The part where they add a script link to the socket.io is where the problem starts. The client side library is never found.

<html>
<head></head>
<body>

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

</body>
</html>

The app.js code looks like this:

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


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

io.on('connection', function(socket){
  console.log('a user is connected')
})

app.listen(3000,function(){
  console.log("Server has started")
})

I have already installed express and socket.io using npm package manager.

When I run the page I get the following error:

enter image description here

UPDATE: This works.

var express = require('express');
var socket = require('socket.io')

var app = express()
var server = app.listen(4000,function(){
  console.log("listening on port 4000")
})

var io = socket(server)

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

io.on('connection', function(socket){
  console.log('a user is connected')
})
john doe
  • 9,220
  • 23
  • 91
  • 167
  • 1
    are you serving static assets with express? – mehulmpt Dec 20 '17 at 18:27
  • How you are you loading the web page into your browser. If you load the web page from `http://localhost:3000/`, then your code should work because the web page comes from your server so the browser will likewise attempt to load `/socket.io/socket.io.js` from the same server. If you load the web page directly from the file system into the browser, then it will not work because the browser will try to load `/socket.io/socket.io.js` from the file system and it will not find it. – jfriend00 Dec 20 '17 at 18:30
  • You need to serve [static files with express.js](https://stackoverflow.com/questions/10434001/static-files-with-express-js) ... that also assumes you have the socket.io file in that directory. – Jordan Kasper Dec 20 '17 at 18:31
  • @jakerella - That is not correct. The socket.io library will automatically server `/socket.io/socket.io.js` from its own directory hierarchy in response to that route request if everything is properly configured. There is no need for explicit static file serving for `/socket.io/socket.io.js`. This is a built-in feature of the server-side socket.io code (that it automatically serves the client-side files). – jfriend00 Dec 20 '17 at 18:34
  • Are you 100% sure you have the proper server-side socket.io library installed on your server because the code, as you show it, will work when properly installed. – jfriend00 Dec 20 '17 at 18:35
  • Thanks! I have updated the question with the solution that worked. Thanks for your help! – john doe Dec 20 '17 at 18:36

0 Answers0