简体   繁体   中英

Socket.io 404 Not Found

For some reason I keep getting " http://127.0.0.1:3000/socket.io/socket.io.js " 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.

Server:

var express = require('express'),
    session = require('express-session');

var app = express();

var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);

var sessionMiddleware = session({
    resave: false,
    saveUninitialized: false,
    secret: 'secret',
    store: new MongoStore({url: "mongodb://localhost:27017/database"})
});

app.use(sessionMiddleware);



io.use(sessionMiddleware, function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);
});

io.sockets.on('connection', function (socket) {
    console.log("Socket connected");
});

app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
   res.render('index');
});

app.listen(3000);
console.log('listening');

Pug File:

html
    head
        script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
        script(type='text/javascript', src='../javascripts/chat.js')
    body

Client javascript:

try {
    var socket = io.connect('http://127.0.0.1:3000');

} catch(e) {
    console.log(e);
}

Change this:

app.listen(3000);

to:

server.listen(3000);

app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.

See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:

websockets, express.js and can't establish a connection to the server


Note, you could use app.listen() , but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:

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

Which is not quite how your code is structured (but you could rearrange things to do it this way).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM