YumeYume
YumeYume

Reputation: 991

Can't get socket.io.js

I'm actually working on a little project, where i'm supposed to recreate a drawing multiplayer game with node.js, mongoDB, socket.io and canvas.

The drawer is working like a charm, and the server seems to work well too. I got my register/login/sessions and database up and working, the only problem is socket.io. When an user is joining the game room, he can see the drawer and tools, but no connection. Why ? The browser can't find socket.io.js.

What I did :

I verified if it was installed, it is with npm install socket.io. I checked if the server was starting it when turning the server on : Got "socket.io started" in my console. I checked my HTML code, here it is :

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

According to the billions of tutorials/dev sites/help subjects, this is supposed to work. But it's not. When opening the console of my browser, I got this :

X GET http://localhost:1337/socket.io/socket.io.js NOT FOUND.

I don't know where is the problem, I can't figure this out and it's giving me a huge headache.. So I'm here.

Thanks in advance for helping ! :)

Upvotes: 20

Views: 37248

Answers (2)

lasec0203
lasec0203

Reputation: 2683

For anyone landing here because they're going through the v4.x socket.io get started example, all you need to do is add another endpoint to your index.js file

index.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

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

// add this
app.get('/socket.io/socket.io.js', (req, res) => {
  res.sendFile(__dirname + '/node_modules/socket.io/client-dist/socket.io.js');
});
///

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

server.listen(3000, () => {
  console.log('listening on *:3000');
});

Upvotes: 4

robertklep
robertklep

Reputation: 203554

Given the code in your comment, you're not using the correct variable for initializing socket.io.

Try this:

var express = require('express');
var app     = express();
var server  = app.listen(1337);
var io      = require('socket.io').listen(server);
...

So instead of having socket.io 'listen' on the Express app instance, it should listen to what app.listen(...) returns (which happens to be an http.Server instance).

Upvotes: 67

Related Questions