Unable to connect to socket.io in production environment - node.js

In development, this is how I was connecting to socket.io:
// server.js
const express = require('express')
const app = express()
const port = 8000
const server = app.listen(port, () =>
console.log(`Server is running on port ${port}`)
);
const io = require('socket.io')(server, {
path: '/socket.io',
pingTimeout: 60000,
cors: {
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-type'],
},
maxHttpBufferSize: 1e8,
});
// App.js
import io from 'socket.io-client';
let socket;
const App = () => {
useEffect(() => {
socket = io(
'http://localhost:8000/',
{ path: '/socket.io' },
{ reconnection: true }
);
}
})
It made sense that in production I should just need to change instances of localhost to my domain, however doing so gave me this error:
net::ERR_FAILED 200 (OK)
From research I learned this was a CORS error, so I then amended my domain in App.js to include the port :8000 but then that brings up this error:
net::ERR_CONNECTION_TIMED_OUT
My site in production is running on https and I have amended my domain in both instances accordingly. I have also enabled the uncomplicated firewall through my host. Hoping someone out there can help me to understand what the issue is.

Related

socket io admin ui not display all information

I am first time experiencing socketio Admin UI. I am facing an issue, I m not abale to view all feature in dashboard. when i visit on https://admin.socket.io/#/ and after successfully login it just shows following menu.
here is my connection snippet.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false
});
I want that all feature as shown in that menu.
Sockets
Rooms
Clients
Events
I found the answer. Actually default mode is development but somehow it was not set when i set the mode to development it works fine for me.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false,
mode: "development"
});
reference : https://socket.io/docs/v4/admin-ui/#mode

run express app and socket.io at the same port with apache reverse proxy

My socket file:
import { Server } from 'socket.io'
import { appConfig } from '#config/app'
const io = new Server(appConfig.socket_port, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
credentials: true
}
})
export { io }
The functions that use the io instance, are like this:
import { io } from '#shared/infra/http/socket'
io.on('connect', socket => {
socket.on(REQUEST_SPREADSHEET_STREAM, async data => {
...
})
})
This works perfectly on localhost, but I'm running express on 3333 and socket.io on 3336. I'm deploying this API on a Compute Engine (GCP) VM, and using PM2 + Apache2 with reverse proxy to the port 3333, but i don't know if it's possible to run the app on a port and the socket on another, both with SSL certificate and both on different ports.
I already tried this approach also:
var express = require('express')
var app = express()
var server = require('http').createServer(app)
var io = require('socket.io')(server)
server.listen(80);
But with this approach, exporting the { io } and using on my functions, they all stop working and typescript says that io is undefined...

WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed. Apply socket.io in ApolloServer nodejs/React is not working

I change from "const socketio = require("socket.io-client");" to "const socketio = require("socket.io");" but it is not working.
the third pic is Back-end and fourth is Front-end. it doesn't say the exact error is but "this.ws =" and "websocket.js:50 WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed: " is all.
you can check in https://socket.io/docs/v4/server-initialization/ i think it's:
io.on("connection",()=>{}) // on server side
if that doesn't work you can try to move all socket code before server.listen it would be something like this:
const http = require('http')
const { Server } = require('socket.io')
const app = require('./app')
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: 'http://localhost:8080',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
},
})
io.on('connection', (socket) => {
console.log("socket",socket);
}
server.listen(process.env.PORT || 5000, () => {
console.log(`Listening on port ${process.env.PORT || 5000}`)
})

Socket io communication blocked by CORS policy in a Node js + Angular application

So I use a simple node.js server with express and socket.io
When I try to communicate with a simple client written in javascript, it works perfectly, but when I try to create the communication with an Angular app (using ngx-socket-io), I get the following error message :
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NQFEnVV' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is the nodejs server :
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 5000;
app.set(port, process.env.PORT);
app.use(express.static('./client/'));
io.on('connection', socket => {
socket.emit('connection', 'data from server!');
});
http.listen(port, () => {
console.log('App listening on port ' + port);
});
And this is how I implement socket.io on Angular client :
app.module.ts :
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const hostname = window.location.hostname;
const url = (hostname === 'localhost') ? `${window.location.protocol}//${hostname}:5000` : undefined;
const config: SocketIoConfig = { url, options: {} };
#NgModule({
declarations: [...],
imports: [
...
SocketIoModule.forRoot(config)
class that use socket io :
constructor(private socket: Socket) { }
this.socket.on('connection', (data) => {
console.log('Working ' + data);
});
I tried to fix the CORS error with headers in server side such as :
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
or
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
but it still display the same error.
I use of course the command ng serve to run my application (running on port 4200) and it was perfectly working 3 months ago. (Working with the ng serve, and the ng build prod as well).
Verify socket.io-client version on the angular packaje.json file. If it's lower than 3.1.2 you could try to upgrade it by
npm install socket.io-client#3.1.2 --save
Also you could verify the serverside once again looking at this
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:4200']
}
});
Replace http://localhost:4200 by your current environmment on the Angular App
try this
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
}
});
you can add or remove mothods
also try adding this
var cors = require('cors');
app.use(cors());
Adding fix from angular side (no changes in Node server required).
That cors: { origins: ['http://localhost:4200']} didn't work for me so I sat up a proxy file in angular project to tackle CORS.
add file in src/proxy.config.js file
{
"/api": { // this attaches /api/ in api url
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
},
"/": { // use this as second entry
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
in angular.json, add this;
"serve": {
"options": {
"browserTarget": "move-safe:build",
"proxyConfig": "src/proxy.config.json"
},
and re-build the angular app
It worked on the local machine but didn't on production.
I was confused why is that happening but suddenly i noticed that the HEROKU deployed it on something like
https://dummydomain.herokkuapp.com
but i was trying to connect it from
http://dummydomain.herokkuapp.com
that may be the reason for your app as well.
:D

Socket.io cors error by using node, react and socket.io

We are using CORS to allow all origins
app.use(cors());
server running on port 4000, and client running on 3000
here is my server.js code
const cors = require("cors");
const http = require("http");
const socketIO = require("socket.io");
app.use(cors());
const port = process.env.PORT || process.env.DEFAULT_PORT;
console.log("port: ", port);
app.listen(port, () => {
console.log(`App listening at ${port}...`);
});
const server = http.createServer(app);
const io = new socketIO(server, {
transports: ["websocket"],
});
React js code
constructor(props) {
super(props);
try {
this.socket = io("http://localhost:4000", { transport: ["websocket"] });
this.socket.on("Chat-event", data => {
console.log("socketdata", data);
});
} catch (error) {
console.log("hiterror", error)
}
}
I am continuously getting this error on the client side after allowing origin for all.
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Mv-SSIc' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
For socket.io version 3.x.x cors configuration has changed, I managed to fix it by adding options to the socket creation.
Tried on the version 2.x.x also and it worked.
const io = socketio(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
Here is the resource https://socket.io/docs/v3/handling-cors/
Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.
By following these steps you can get rid of these error.
// 1) on server side
const cors = require('cors');
const socketio = require('socket.io')
const http = require('http');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: localhost:3000/, //your website origin
methods: ["GET", "POST"],
credentials: true
}
});
// 2) add these middlewares
app.use(cors())
app.options('*', cors());
// 3) on client-side
import io from 'socket.io-client'
let socket = io.connect(localhost:8080, { transports: ['websocket'] }) // your local server
try using the cors credentials config:
app.use(cors({credentials: true}));
Please allow all to socket.io at server side
const socketIO = require('socket.io')(server, { origins: '*:*'});
Or you can set socketIO origins as *
socketIO.set('origins', '*:*');
#user4860402 Gave me solution, thing is that by default npm is installing socket.io client v 2.X.X but on server I'm using latest verion (also provided by npm) 3.0.5
So all problems including 400 error comes because client and server verion doesnot match.
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const socketio = require("socket.io");
const cors = require("cors");
const io = socketio(http, {cors:{origin:"*"}});

Resources