connect by socket.io for react native and sails - node.js

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.

Related

Socket.io based server is inaccessalbe to socket connections, but the troubleshooting link works

Pretty much, my socket.io server lets me access <the server URL>/socket.io/?EIO=4&transport=polling (which is the troubleshooting step in the docs), but it doesn't let me connect to the websocket normally.
This happens when I try to connect to the websocket in postman:
Pic1
Here is my code:
let server = require('http').createServer()
const io = require('socket.io')(server)
server.listen(5000)
console.log('init complete')
I've rewritten this using multiple tutorials online to MAKE SURE it's right, but no matter what I follow it just doesn't work.

Nodejs ssl3_get_record wrong version number

For the past few months I've been working on a project involving Nodejs (12.16.1).
I've created a backend API (database and other resources) and an authentication service. Im currently updating a Discord bot that uses nodejs (all using the same node version and same node-fetch).
The bot is having issues connecting to the Backend API. Using node-fetch with the following error
request to https://<host:port>/api/bot/<resource> failed, reason: write EPROTO 1988:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\\ws\\deps\\openssl\\openssl\\ssl\\record\\ssl3_record.c:332:\n
Im not using a Proxy, infact its a dev environment all running under localhost. Which has been running without an issue for months.
Now for the interesting part. The bot will POST fine to the authentication service but will fail when using POST or GET to the Backend. Postman will have no issue accessing the APIs. Thinking it was the certificate I made a new one (self-signed) but i still get the same error message.
So I used Wireshark and captured the traffic between the Bot the Authentication service and the Backend. When the bot talks to the Authentication services it does the Hello client / server messages in TLS 1.3. However when it talks to the backend it tries to use TLS 1.0.
Thinking any new current code was causing issues i pulled a fresh copy of the Backend and the Bot from my repo and tried again. Even the current Live builds will fail with the same error message.
I have no clue what is going, I've only been coding for a few months and this is the first wall I've hit that i can't seem to figure out. Goolge and even stack hasn't been much help as an ssl3 wrong version errors have been left unanswered or don't line up with my issue (most people seem to have this issue when using Proxies).
The only thing that has updated software wise was the latest Windows 10 updates.
KB4598242, KB4023057
Thanks.
Edit.
server.js
const port = process.env.PORT;
const key = fs.readFileSync('./server.key');
const cert = fs.readFileSync('./server.cert');
app.use(jwt());
app.use(express.json());
app.use(cors());
app.use('/api/bot', require('routes/botapi'));
const server = https.createServer({'key': key, 'cert': cert}, app);
server.listen(port, () => { console.log(chalk.green(`[SERVER]`) + `: listening on ${port}`) });
botapi.js
...requires
const botRouter = express.Router();
botRouter.post('/updatemembers', discordUpdateMembers);
async function discordUpdateMembers(req, res, next) {
let validRole = await hasBotRole(req);
if (!validRole) return res.status(400).send({err: 'Access_Denied!!'});
discord.updateMembers(req.body)
.then(members => members ? res.json(members) : res.status(400))
.catch(err => next(err));
}

Run a VPN client on a remote website

I have been researching this for day and I haven't been able to find the way to do this.
I am building a react app, running express at the backend, that needs to access some data in a remote database that lives inside a VPN. At the moment the app lives on my localhost so its enough for me to connect my machine using openvpn client and everything works a beauty. The problem will rise when the app will be live and I will need it to have access to the vpn by (I'm guessing) having a vpn client running on the site/domain.
Has anyone done this before?
I have tried to install the node-openvpn package that seems could do the job but unfortunately I can't manage to make it work as the connection doesn't seem to be configured properly.
This is the function I call to connect to the vpn that systematically fails at the line
--> openvpnmanager.authorize(auth);
const openvpnmanager = require('node-openvpn');
...
const connectToVpn = () => {
var opts = {
host: 'wopr.remotedbserver.com',
port: 1337, //port openvpn management console
timeout: 1500, //timeout for connection - optional,
logpath: '/log.txt'
};
var auth = {
user: 'userName',
pass: 'passWord',
};
var openvpn = openvpnmanager.connect(opts);
openvpn.on('connected', function() {
console.log('connecting..');
openvpnmanager.authorize(auth); <-- Error: Unhandled "error" event. (Cannot connect)
});
openvpn.on('console-output', function(output) {
console.log(output)
});
openvpn.on('state-change', function(state) { //emits console output of openvpn state as a array
console.log(output)
});
};
Am I misusing this function? Is there a better way?
Any help will be extremely appreciated.
Thank You!
The problem will rise when the app will be live and I will need it to
have access to the vpn by (I'm guessing) having a OpenVPN client running
on the site/domain.
Thats correct, you will need an openvpn client instance on the server where you will run the backend.
The above library (node-openvpn) is simply a library to interact with the local OpenVPN client instance. It cannot create a connection on its own. It depends on the OpenVPN binary (which should be running).
The solution you need is simply run the OpenVPN client on your server (apt-get openvpn). And let the daemon run. Check out the references below.
node-openvpn issues that points out that a running instance of the client is needed
OpenVPN CLI tutorial

AZURE + SOCKET.IO: How do I know which port my Web App is using?

I went to a Hackathon last weekend and a Microsoft recruiter set me up with Azure for my Node.js project.
We used Socket.io with my project and had a hard time connecting the Client to the Server because we didn't know which port to connect to...
On our WebApp (not Azure VM), we had the following code:
var port = process.env.port || 3000;
On the client side of Socket.io, I had to specify an ip address to use along with it's port. I tried:
var socket = io('http://IP.AD.DRE.SSS:3000'); //And
var socket = io('http://IP.AD.DRE.SSS'); //And even a different Port
var socket = io('http://IP.AD.DRE.SSS:9999'); //And 443 and 80
And every iteration... I had to be doing something wrong. We ended up switching over to Digital Ocean because I knew how to use it but I really wanted to get this working.
Any Ideas?
UPDATE:
I changed it to 80 and my current error is: "Access Control Allow Origin." Note: My client is running on a server.
UPDATE 2: Return of the OP
Unfortunately, the CORS package for Node did not do the trick...
Some more info:
I'm not using Express or Connect. My server is on Azure (as an Azure Web App). My Client was on Localhost (Thanks to WebStorm).
Azure Web Apps only listens on ports 80 & 443. Change the port to either of them and your app will work fine.
Just leave the port off in the client string. You can connect using the URL alone. Look at my code I codefoster.com/commandmonkey as an example.

Websocket server running fine but cannot connect from client (what url should I use?)

OK this is very simple to anyone who's used websocket and nodejs.
I have created a websocket server named ws_server.js and put it in C:\Program Files (x86)\nodejs where I have installed the nodejs framework. I started the server and it is running and it says it's listening on port 8080. So far so good, I have the server running.
Now I simply want to connect to it from client code so that I can do all that lovely stuff about capturing events using event listeners etc. The problem is, embarassingly, I cannot figure out what URL to use to connect to my websocket server.
function init() {
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket("ws://localhost:8080/"); // WHAT URL SHOULD BE USED HERE?
websocket.onopen = function(evt) { alert("OPEN") };
websocket.onclose = function(evt) { alert("CLOSE") };
websocket.onmessage = function(evt) { alert("MESSAGE") };
websocket.onerror = function(evt) { alert("ERROR") };
}
function doSend(message) {
// this would be called by user pressing a button somewhere
websocket.send(message);
alert("SENT");
}
window.addEventListener("load", init, false);
When I use ws://localhost:8080 the only events that trigger are CLOSE and ERROR. I cannot get the client to connect. I must be missing something very simple. Do I need to set up my nodejs folder in IIS for example and then use that as the URL?
Just to reiterate, the websocket server is running fine, I just don't know what URL to use to connect to it from the client.
EDIT: The websocket server reports the following error.
Specified protocol was not requested by the client.
I think I have got it working by doing the following.
var websocket = new WebSocket("ws://localhost:8080/","echo-protocol");
The problem being that I needed to specify a protocol. At least now I get the onopen event. ...if nothing much else
I was seeing the same error, the entire web server goes down. Adding the protocol fixes it but leaves me wondering why it was implemented this way. I mean, one bad request should not bring down your server.
You definitely have to encase it a try/catch, but the example code provided here https://www.npmjs.com/package/websocket (2019-08-07) does not. This issue can be easily avoided.
I just wanted to share a crazy issue that I had. I was able to connect to a websocket of an old version of a 3rd party app in one computer, but not to a newer version of the app in another.
Moreever, even in new computer with the new version of the app, The app was able to connect to the websocket, but no matter what I did, when I tried to connect with my own code, I kept getting the error message that the websocket connection failed
Long story short, They changed an apache configuration that allowed connecting to the websocket via a proxy.
In the old version, apache config was:
ProxyPass /socket/ ws://localhost:33015/ retry=10
ProxyPass /socket ws://localhost:33015/ retry=10
In the new version, apache config was changed to:
ProxyPass /socket/ ws://localhost:33015/ retry=10
By bad luck, I was trying to connect to ws://localhost/socket and not to ws://localhost/socket/. As a result, proxy was not found, and connection returned an error.
Moral of the story: Make sure that you are trying to connect to a websocket url that exists.
For me, the solution was to change the URL from ws:// to wss://. This is because the server I was connecting to had updated its security, and now only accepted wss.

Resources