1
votes

I'm trying to connect socket.io on Angular and Nodejs server In Angular I have declared a new socket and connect it

import * as io from 'socket.io-client';
...
@component
...
const socket = io.connect('http://localhost:3000');

In back end : server.js

const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.set('origins', 'http://localhost:4200');

var routes = require('./routes/routes')(io);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:4200");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
    res.header('Access-Control-Allow-Credentials', true);

    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
});
io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    console.log("connectd");
});
app.use('/', routes);
var server = app.listen(3000, function (io) {
})

The app is compiling and getting data from server. but only socket.io is not working I get this error:

GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpN9Qy 404 (Not Found)

1

1 Answers

2
votes

socket.io is attached to http:

var http = require('http').Server(app);
var io = require('socket.io')(http);

so you have to use:

http.listen(3000) 

instead of

app.listen(3000) // This will only start an express server

Your socket server never starts, that's why you're getting a 404, since only express is running.