socket connection always failing

2019-08-10 00:38发布

问题:

I'm writing an application that connects to a sails server.

This application is written with cordova, angularJS and Ionic.

When I launch my application in my browser (with ionic serve) the socket fails to connect to the server. Here is the message I get:

GET http://localhost:8100/socket.io/?__sails_io_sdk_version=0.11.0&__sails_io_s…sails_io_sdk_language=javascript&EIO=3&transport=polling&t=1443472067762-4 404 (Not Found)

The server is running locally on port 1337. I tried to change the above URL to:

http://localhost:1337/socket.io/?__sails_io_sdk_version=0.11.0&__sails_io_s…sails_io_sdk_language=javascript&EIO=3&transport=polling&t=1443472067762-4

and it's working.

In my code I set the URL after sails.io.js has been included:

io.sails.url = 'http://localhost:1337';
io.sails.useCORSRouteToGetCookie = false;

Why is it asking to localhost:8100 and not localhost:1337?

When I launch this application in my mobile device (setting the url to http://192.168.1.10:1337) it's working correctly.

Version of sails.io.js is 0.11.6, and version of sails is 0.11.0

回答1:

localhost:8100 wont work in your mobile development environment. I faced same issue and changing localhost to your workstation's ip solved the problem



回答2:

I finally found the solution (but I'm sorry I can't recall where I found it :()

The problem was that the io.sails.url = 'http://localhost:1337'; was executed after the first JS cycle, and thus the sails socket was already loaded. (that's (from what I understood) because in some browsers if the code is in another script tag it is executed in another cycle)

To make it work I had to add this code before I include the sails socket script:

var apiHost = 'localhost';
            (function (){
                var io;
                Object.defineProperty(window, 'io', {
                    get: function (){
                        return io;
                    },
                    set: function (value){
                        var sails;
                        io = value;
                        Object.defineProperty(io, 'sails', {
                            get: function (){
                                return sails;
                            },
                            set: function (value){
                                sails = value;
                                sails.url = 'http://'+apiHost+':1337';
                                sails.useCORSRouteToGetCookie = false;
                            }
                        });
                    }
                });
            })();