【问题标题】:Ionic app won't connect to Socket.IO离子应用程序不会连接到 Socket.IO
【发布时间】:2015-12-31 15:46:38
【问题描述】:

我为 Socket.IO 连接设置了一个小型节点应用程序:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log('socket connected');

    socket.on('disconnect', function () {
        console.log('socket disconnected');
    });

    socket.emit('text', 'wow. such event. very real time.');
});

server.listen(3000, function() {
    console.log('Socket.io Running');
});

在我的 Ionic 应用程序中,我有以下内容:

$ionicPlatform.ready(function(device) {
    var socket = io('http://192.168.1.9:3000');

    if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
        StatusBar.styleDefault();
    }
    alert('here');
    $state.go('signin');
});

当 Ionic 应用程序启动时,我得到了显示的警报,因此我知道 platform.ready 事件正在触发。但是 Ionic 应用程序永远不会连接到服务器上的套接字会话。

如果我使用 Chrome 检查 Ionic 应用程序,我会记录以下错误:

Failed to load resource: the server responded with a status of 404 (Not Found) http://192.168.1.9:3000/socket.io/?EIO=3&transport=polling&t=1443883896073-0
Failed to load resource: the server responded with a status of 404 (Not Found) http://192.168.1.9:3000/socket.io/?EIO=3&transport=polling&t=1443883899867-1
Failed to load resource: the server responded with a status of 404 (Not Found) http://192.168.1.9:3000/socket.io/?EIO=3&transport=polling&t=1443883901481-2
Failed to load resource: the server responded with a status of 404 (Not Found) http://192.168.1.9:3000/socket.io/?EIO=3&transport=polling&t=1443883904606-3

但是IP地址和端口号是正确的。

为什么 Ionic 不能连接到 Socket.iO?

编辑 - 2015 年 4 月 10 日

我的 Ionic 项目正在使用 cordova-plugin-whitelist 插件,并且我在 index.html 中添加了内容安全策略 <meta> 标记。

编辑 05/10/2015

我也尝试过移除并重新添加 Android 平台,但仍然无法正常工作。

【问题讨论】:

  • 本地系统中的节点服务器项目和离子项目?

标签: javascript node.js socket.io ionic


【解决方案1】:

可能存在 CORS 错误,

请使用此配置

let io = require('socket.io')(server, {
    origins: ["*"],
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
})

这将解决您的问题。

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 2021-06-20
    • 2016-12-12
    • 2019-07-19
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多