[英]Socket.io + NodeJS IONIC CORS issue
I hope you are doing well.我希望你做得很好。
I am currently facing an issue with my IONIC application.我目前正面临我的 IONIC 应用程序的问题。
Setup:设置:
Here's the code I am using on IONIC side:这是我在 IONIC 端使用的代码:
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
:当我使用
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.我在 Android 设备上使用 APK 构建实验同样的问题。
But my other "non socket-io" requests on my express API are just performing fine from IONIC side.但是我对我的快递 API 的其他“非套接字 io”请求在 IONIC 方面表现良好。
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.与
socket.io-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:看起来您需要将 CORS 添加到 io 实例:
For v2.xx对于 v2.xx
require('socket.io')(server, {
origins: [`http://localhost:${config.port}`]
})
https://socket.io/docs/v2/handling-cors/ https://socket.io/docs/v2/handling-cors/
For v3.xx:对于 v3.xx:
require('socket.io')(server, {
cors: {
origin: `http://localhost:${config.port}`,
methods: ['GET', 'POST']
}
})
https://socket.io/docs/v3/handling-cors/ 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.我不确定您是否需要 CORS 在 express 应用程序上,因为您似乎只使用 sockets 但这当然取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.