Why doesn’t anyone plug into my socket.io?

Asked

Viewed 66 times

1

Hello!

I have an api with the following example code:

const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const cors = require('cors')

app.use(cors())
app.get('/', (req, res)=>{
    io.emit('teste', {status: true})
    res.send('socket.io')
})

app.get('/socket.io', (req, res)=>{
    res.send(req.params)
})


app.post('/socket.io', (req, res)=>{
    res.send(req.body)
})
io.on('connection', socket => {
    console.log('concted');
    socket.on('connect', data =>{
        io.emit('teste', true)
    })
    socket.on('teste', teste =>{
        socket.emit('teste', teste)
    })
})

app.listen(4000, ()=>{
    console.log('listen on 4000');
})

I’m using as dependency:

"cors": "^2.8.5",
"express": "^4.17.1",
"socket.io": "^3.0.4"

<html>
    <head>
        <title>Document</title>
    </head>
    <body>    
        <script src="socket.js"></script>    
        <script>
            var socket = io('http://localhost:4000')
            socket.on('teste', data =>{
                console.log('test');
            })
        </script>
</body>
</html>

The javascript content I copied from here

When accessing the page does not appear that connected

In api, change Listen to

http.listen(4000, ()=> {
})

While trying to access through the html page, I have this result in the console

I have Cors problem

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

I’ve tried so many ways

/*
var whitelist = ['http://localhost']
const options = (req, callback) =>{
  var corsOptions;
  if (whitelist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  } else {
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}*/
var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 
  }
  app.use(cors(corsOptions));

//app.use(cors(options))
app.use((req, res, next) =>{
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
  • I think the protocol should be ws:// and not http://, can be wrong never used the socket.io specifically.

  • 1

    also does not connect

  • About the error presented CORS I saw that you are using app.use(cors()) but he keeps complaining that it’s not allowed, that’s a related question that might help: CORS on Nodejs without the use of Frameworks

  • I believe that it is not return and yes, the frontend to have access to the back

1 answer

0


I found out.

After so much research, Findei finding where to search using firefox

In the socket.io statement.

const io = require('socket.io')(http)

I changed it to this

const io = require('socket.io')(http, {
    cors: {
        origin: "http://localhost",
        methods: ["GET", "POST"]
      }
})

In case someone has the same problem I do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.