How to configure socket.io client for backend access
-
I’ve made a simple web app that consists on a nodejs scheduler backend and a quasar spa frontend that connects using socket.io.
I know how to configure the client to connect on localhost, but if I try to open the same frontend on another device on the network, logically can’t connect.
Taking into account that I will host both server and client on a docker container, how I can configure socket.io to be reachable outside localhost?Backend:
const app = require('express')(); const http = require('http') .createServer(app) .listen(config.socketPort, config.socketIP, function() { // Being: 0.0.0.0:3002 console.log( `socket: websocket listening on ${config.socketIP}:${config.socketPort}` ); const io = require('socket.io')(http, { cors: { origin: '*' }, }); ...
Frontend:
import io from 'socket.io-client' const socket = io.connect('http://localhost:3002') export default ({ Vue }) => { Vue.prototype.$socket = socket } export { socket }
-
You have to set the server listening IP to it’s IP address instead of 0.0.0.0:3002 . The client (Quasar that runs on someone’s browser, not server) has to connect to the nodejs server’s IP address and not localhost.
-
@dobbel said in How to configure socket.io client for backend access:
You have to set the server listening IP to it’s IP address instead of 0.0.0.0:3002 . The client (Quasar that runs on someone’s browser, not server) has to connect to the nodejs server’s IP address and not localhost.
Thanks dobbel for your help.
The question is how to get this IP, so I can pack the app into a docker container and if a friend (that doesn’t have cli or programming skills at all) installs it, he doesn’t have to get the IP and alter his sources and repack.
It would be nice if it’s possible to get that IP in code, and also transmit it to the web client.I’ve tried to setup a env-to-config var module, on both backend and frontend, and use dotenv to set the IP at development time.
// /src/config/index.js module.exports = { mqttServer: process.env.MQTT_SERVER, hostIP: process.env.HOST_IP || '0.0.0.0', socketIP: process.env.IP || '0.0.0.0', socketPort: process.env.SOCKET_PORT || 3002 }
// boot/socket.js import io from 'socket.io-client' const config = require('src/config') const hostIp = config.hostIP.replace(/['"]+/g, '') // quasar-dotenv adds %22 chars const socket = io.connect(`http://${hostIp}:${config.socketPort}`) export default ({ Vue }) => { Vue.prototype.$socket = socket } export { socket }
It works in development, with the related .env file. But I’ve tried to setup the HOST_IP var like
export HOST_IP=xx.xx.xx.xx
and thenquasar dev
in the same terminal, but it doesn’t get the var.
It would be nice to have that IP in a var.