祝你一切顺利。
我的IONIC应用程序目前面临一个问题。
设置:
- 安装了ngx-socket-io模块的IONIC 5应用程序
- NodeJS后端,带有express API和socket。io服务器监听xxx.xxx.xxx.xxx:3000
- 插座。IO和socket。io-client都在2.4.0版本
这是我在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));
当我使用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.
我在Android设备上使用APK构建时遇到了同样的问题。
但我的其他"非插座"我的快速API的请求只是执行良好的IONIC侧。
下面是我写的后端代码:
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-client
可以很好地模拟客户端。
在这种情况下会出什么问题呢?
感谢您提供的任何帮助或建议。
看起来您需要将CORS添加到io实例:
为v2.x.x
require('socket.io')(server, {
origins: [`http://localhost:${config.port}`]
})
https://socket.io/docs/v2/handling-cors/
v3.x.x:
require('socket.io')(server, {
cors: {
origin: `http://localhost:${config.port}`,
methods: ['GET', 'POST']
}
})
https://socket.io/docs/v3/handling-cors/
我不确定你是否需要CORS在快速应用程序,因为你似乎只使用套接字,但这当然取决于你。