Localhost socket.io server not found (404)

  angular, javascript, socket.io

I’m trying to hook up a socket.io server in Express to an Angular client, and I’m hitting some snags.

Currently my code for my Express program is

const options: cors.CorsOptions = {
    allowedHeaders: [
        'Origin',
        'X-Requested-With',
        'Content-Type',
        'Accept',
        'X-Access-Token',
    ],
    credentials: true,
    methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
    origin: ['http://localhost:4200/'],
    preflightContinue: false,
};

dotenv.config();
const app: Express = express();
app.use(bodyParser.json())
app.use(cors());


let server = http.createServer(app);
let io = new socketio.Server(server);
// let io = new socketio.Server();
// io.listen(server);

io.on('connection', (socket) => {
    console.log("Connection from client");
})

app.listen(process.env.PORT, () => {
    return console.log(`server is listening on ${process.env.PORT}`);
});

This works fine for normal HTTP, I’ve had this working and I’m not getting CORS errors or anything. However when I try to connect to Angular client to the server, I start getting 404 errors.

GET http://localhost:5050/socket.io/?EIO=4&transport=polling&t=Nb8aNZ5 404 (Not Found)

I’ve had a bit of a look and I’ve found this stack overflow answer that mentions the following code

var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
server.listen(app.get('port')); // not 'app.listen'!

I get the 404 error when using app.listen(port), however if I then change that to server.listen(port) I start getting CORS errors trying to connect to the socket.io server from the client.

Access to XMLHttpRequest at 'http://localhost:5050/socket.io/?EIO=4&transport=polling&t=Nb8bDGb' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I’m not sure what I need to change here to get this working. I’d like to be able to use app.listen so that I can use all of my express middleware. Is there a way I can do that?

The client uses the following to try and connect

import * as socketioClient from 'socket.io-client';
this.socket = socketioClient.io(environment.apiBaseUrl); //Url is http://localhost:5050

Source: Ask Javascript Questions

LEAVE A COMMENT