简体   繁体   中英

Socket.io + NodeJS IONIC CORS issue

I hope you are doing well.

I am currently facing an issue with my IONIC application.

Setup:

  • IONIC 5 Application with ngx-socket-io module installed
  • NodeJS Back-End with express API and socket.io server listening on xxx.xxx.xxx.xxx:3000
  • socket.io and socket.io-client both in version 2.4.0

Here's the code I am using on IONIC side:

this._storage.get(`setting:loginToken`).then(setToken => {
      alert("Connecting to socket.io server...")
      this.socket.connect();
      alert("Should be connected...")
      this.socket.emit('authenticate', { token: setToken });
      alert("Auth token sent")
    }, error => console.log(error));

This is what i'm getting in my browser developer tools when I am running the application with ionic serve :

Blocking a Cross-Origin Request: The "Same Origin" policy does not allow consulting the remote resource located at http://XXX.XXX.XXX.XXX:3000/socket.io/?EIO=3&transport=polling&t=NTkQPqH. Reason: The CORS header "Access-Control-Allow-Origin" is missing.

I experiment the same problem using the APK build on an Android device.

But my other "non socket-io" requests on my express API are just performing fine from IONIC side.

Here is the back-end code I wrote:

const app = express();
app.use(cors());

var server = app.listen(config.port, () => {
  console.log('Server is listening on %d in %s mode.', config.port, app.get('env'));
});

var io = require('socket.io')(server)
const socketioJwt = require('socketio-jwt');

io.sockets
  .on('connection', socketioJwt.authorize({
    secret: 'stackoverflow',
    timeout: 15000
  }))
  .on('authenticated', (socket) => {

    socket.on("disconnect", () => {
    })

  });


Connecting with socket.io-client works just fine to simulate a client.

What can be wrong in this situation?

Thank you for any help or advices you can provide.

Looks like you need to add the CORS to the io instance:

For v2.xx

require('socket.io')(server, {
  origins: [`http://localhost:${config.port}`]
})

https://socket.io/docs/v2/handling-cors/

For v3.xx:

require('socket.io')(server, {
  cors: {
    origin: `http://localhost:${config.port}`,
    methods: ['GET', 'POST']
  }
})

https://socket.io/docs/v3/handling-cors/

I'm not sure if you'll need CORS on the express app since you seem to be using sockets exclusively but that's up to you of course.

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