简体   繁体   中英

GET /socket.io/?EIO=3&transport=polling&t=NZFvwqb 404 149

I got the above exception when I try to implement socket.io to count active users, i tried every solution but nothing works for me.

Server:

const express = require("express");
const app = express();
const cors = require("cors");
const socketIo = require('socket.io');
const http = require('http');

//Enable CORS policy
app.use(cors());
app.options("*", cors());

//socket io
const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origins: ["http://localhost:4200", "http://localhost:3000"],
        methods: ["GET", "POST"],
        credentials: false
    }
});


var count = 0;
io.on('connection', (socket) => {    
  console.log("Client connected");    
    if (socket.handshake.headers.origin === "http://localhost:3000") {
        count++;        
        socket.broadcast.emit('count', count);               
        
        socket.on('disconnect', () => {
            count--;                   
            socket.broadcast.emit('count', count);            
        });
    }   
}); 

//Server
app.listen(8080, () => {
  console.log("Server is running on port 8080");
});

Change this:

app.listen(8080, () => {
  console.log("Server is running on port 8080");
});

To this:

server.listen(8080, () => {
  console.log("Server is running on port 8080");
});

You are facing this issue because the instance you've passed when initializing socket and instance you are listening to are different.

For more refer this: Should I create a route specific for SocketIO?

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