简体   繁体   中英

connect by socket.io for react native and sails

I am trying to connect mobile app with react native and nodeJS running with sails I have test the connection with reactJS and the socket work fine on the browser but with react native it give me this error

The socket was unable to connect.
The server may be offline, or the
socket may have failed authorization
based on its origin or other factors.
You may want to check the values of
`sails.config.sockets.onlyAllowOrigins`
or (more rarely) `sails.config.sockets.beforeConnect`
in your app.
More info: https://sailsjs.com/config/sockets
For help: https://sailsjs.com/support

I have tried to add onlyAllowOrigin and add on it the url for connect and I have added origin in the header for the frontend part but all didn't work

this is the setup I used in frontend

let socketIOClient = require('socket.io-client');
let sailsIOClient = require('sails.io.js');
let token = 'my jwt token'
let io = sailsIOClient(socketIOClient);
io.sails.url = 'http://localhost:1337/';
io.sails.headers = {authorization:token,origin:'http://localhost:3000'}

 useEffect(() => {
        io.socket.on('my event',(data) => {
            console.log({data})
        })
})

backend setup

var io = sails.io
 io.emit('my event, {data:'my data'});

I think your issue may be that, as you said you are testing on a 'device' if that is the case then

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

Will not work, the device has no access to localhost, you need to make the socket server publicly available, even if you are using wifi. Localhost is just that, local to the host. Your app can access it on the desktop because, well its local but when its on the device it will try and connect to itself on port 1337, but nothing is running there so its failing.

I would suggest just pushing your code to a public server of some sort (socket server that is)

Some inexpensive / free location are

  • AWS (free tier)
  • Digital Ocean ( 100.00 credit or 5.00 / month)
  • Linode (100.00 credit or 5.00 / month)

There are many others, but these are some popular ones, also with all options they have pre configured node instances that make it easy to get up and running quickly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM