User
User

Reputation: 194

Socket.io version 2.1.0 error 404

I found this error using socket.io latest version: "index.js: 83 POST http: //localhost/socket.io/? EIO = 3 & transport = polling & t = MDUHEO9 404 (Not Found)". I understand the reason: the true address must be http: // localhost: 3000 / socket.io /. Do you know how I can correct?

I have read many discussions, but no one has a suitable solution for version 2.1.0, even in a discussion I read a downgrade proposal, I would like to avoid it.

client.js:

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io().connect('http://localhost:3000');
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>

server.js:

var app = require('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){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

Upvotes: 0

Views: 344

Answers (2)

jfriend00
jfriend00

Reputation: 707258

Change this:

var socket = io().connect('http://localhost:3000');

to this:

var socket = io.connect('http://localhost:3000');

or to this:

var socket = io('http://localhost:3000')

Either of these last two are the same.


You will want to use only one form of connect, either io(...) or io.connect(...), not both. When you call just io() you're trying to connect to the default URL which will be the URL of the current web page and then when you then try to also do .connect() after that, you're trying to connect again. You only want one connection and to the specified URL.

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

The problem here is that you've defined any endpoint to server socket.io client file. That's why you are getting 404.

If you've installed in with npm, you can allow express to server that kind of static files for you by just adding the following line

app.use(express.static(__dirname + '/node_modules'));  

if you've installed socket.io with bower, use

 app.use(express.static(__dirname + '/node_modules'));  

Or you can place that socket.io's client library at any location and server the file against the requests like

app.get('/socket.io', function(req, res){
  res.sendFile("Path to socket.io.js file");
});

And you don't need to write full address in

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

Just use

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

Upvotes: 1

Related Questions