Ad

I Get An Error Trying To Connect My Backend With Socket.io

- 1 answer

I get the next error when I try to connect my server with Socket.io. I'm making an app with angular and node and this is what I get:

Solicitud de orígenes cruzados bloqueados: La misma política de origen deshabilita la lectura remota del elemento en ‘http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MhGdqdk’. (Razón: La credencial no está soportada si el encabezado CORS ‘Access-Control-Permitir-Origen' está ‘*’).

URL pedida:http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MhGe0a7
Método de la solicitud:GET
Dirección remota:127.0.0.1:3000
Código del estado:404

// Requires and const definition
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const mongoURI = "mongodb://localhost:27017/proyecto_daw";
const http = require('http');
const normalizePort = require('normalize-port');

// Configuración CORS
app.use((req, res, next) => {
   res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
   res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
   res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
   next();
});

// Middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// Routes
const user_routes = require('./routes/user.routes');
const follow_routes = require('./routes/follow.routes');
const group_routes = require('./routes/groups.routes');
const publication_routes = require('./routes/publication.route');
app.use('/api', user_routes);
app.use('/api', follow_routes);
app.use('/api', group_routes);
app.use('/api', publication_routes);


var server = http.createServer(app);
var io = require('socket.io').listen(server);

io.on('connection',(socket)=>{

 console.log('new connection made.');


 socket.on('join', function(data){
   //joining
   socket.join(data.room);

   console.log(data.user + 'joined the room : ' + data.room);

   socket.broadcast.to(data.room).emit('new user joined', {user:data.user, message:'has joined this room.'});
 });


 socket.on('leave', function(data){

   console.log(data.user + 'left the room : ' + data.room);

   socket.broadcast.to(data.room).emit('left room', {user:data.user, message:'has left this room.'});

   socket.leave(data.room);
 });

 socket.on('message',function(data){

   io.in(data.room).emit('new message', {user:data.user, message:data.message});
 })
});


// Database
mongoose.Promise = global.Promise;
mongoose.set('useFindAndModify', false);
mongoose.connect(mongoURI, { useNewUrlParser: true })
 .then(() => {
   console.log("BD conectada");

   // Creación del servidor
   app.listen(app.get('port'), () => {
     console.log("Puerto " + app.get('port'));
   })
 })
 .catch(err => console.log(err));

Ad

Answer

require('socket.io') returns a function that constructs the socket object which you should provide the server to.

Thus that's what you should do:

var socketIO = require('socket.io');
var theSocketObject = socketIO(server);

And then use the theSocketObject to emit/listen to events.

Ad
source: stackoverflow.com
Ad