Node.js Socket.io+;NodeJS离子CORS问题

Node.js Socket.io+;NodeJS离子CORS问题,node.js,sockets,ionic-framework,socket.io,Node.js,Sockets,Ionic Framework,Socket.io,我希望你做得很好 我目前面临着离子应用程序的问题 设置: 安装ngx插座io模块的IONIC 5应用程序 NodeJS后端,带有express API和socket.io服务器,监听xxx.xxx.xxx.xxx:3000 版本2.4.0中的socket.io和socket.io-client 以下是我在爱奥尼亚方面使用的代码: this._storage.get(`setting:loginToken`).then(setToken => { alert("Co

我希望你做得很好

我目前面临着离子应用程序的问题

设置:

  • 安装ngx插座io模块的IONIC 5应用程序
  • NodeJS后端,带有express API和socket.io服务器,监听xxx.xxx.xxx.xxx:3000
  • 版本2.4.0中的socket.io和socket.io-client
以下是我在爱奥尼亚方面使用的代码:

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));
当我使用
爱奥尼亚服务
运行应用程序时,这就是我在浏览器开发工具中得到的:

阻止跨源请求:“同一源”策略不允许咨询位于的远程资源http://XXX.XXX.XXX.XXX:3000/socket.io/?EIO=3&transport=polling&t=NTkQPqH. 原因:CORS标题“访问控制允许来源”缺失。

我在Android设备上使用APK构建来试验同样的问题

但我的expressapi上的其他“非套接字io”请求从爱奥尼亚的角度来看运行良好

以下是我编写的后端代码:

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", () => {
    })

  });


连接socket.io客户端可以很好地模拟客户端

在这种情况下会出现什么问题


感谢您提供的任何帮助或建议。

看起来您需要将CORS添加到io实例:

对于v2.x.x

require('socket.io')(服务器、{
起源:[`http://localhost:${config.port}`]
})

对于v3.x.x:

require('socket.io')(服务器、{
cors:{
来源:`http://localhost:${config.port}`,
方法:['GET','POST']
}
})

我不确定您是否需要在express应用程序上使用CORS,因为您似乎只使用套接字,但这当然取决于您