Esteban Subissi
Esteban Subissi

Reputation: 11

Using socket-io (backend) inside AWS EC2 Container under path "/api" and ngx-socket-io (client side front-end)

I've been implementing websockets to comunnincate frontend and backend. Backend is NodeJS (Socket-io library V4.0.0) Frontend is Angular ( ngx-socket-io library V4.1.0).

The implementation works fine when running in localhost (http://localhost:port). Frontend connects to socket adding default path to url localhost:port/socket.io

The problem happens when the application is deployed on Amazon ECS (docker containers) because it's configured to use same url for both front and back.
If path starts with "/api" it points to backend (example: https://mydns.com/api/login). Otherwise, any other route without starting with /api will point to the frontend routes.

On this "production stage" frontend client isn't getting socket messages from server. I can see in browsers console that the frontend socket library its making 4 requests: First one response is OK Second one displays an error: "Invalid namespace". Third and fourth are random strings.

**Node socket.io implementation: ** `.
const params = { cors: { origin: '*', } } const io = require('socket.io')(server, params);

io.on('connection', (socket) => {
    console.log('New connection from ' + socket.request.connection.remoteAddress);
  
      socket.on('userInit', (data)=>{
        console.log("USER LOGGED IN: " + data,);
        io.emit("userLoggedIn", data)
      })
    });
    
io.on('disconnect', function () {
  console.log('User disconnected');
});

`

Angular ngx-socket-io implementation: `.
@Injectable({ providedIn: 'root' }) export class SocketWebServiceService extends Socket {

  constructor() {
    super({ 
       url:  environment.apiUrl,  
       options: environment.production?{ path: "/api/socket.io"}:{}
    });
   }

`

As I could see, ngx-soket-io wont use the full apiUrl (it removes the "/api") that's why in production build I add the param "path" to "/api/socket.io" when initializing websocket.

I know it's a difficult question, sorry about that. Thanks in advance.

Im expecting to messages sent by server socket work the same as when I run it in local stage.

Upvotes: 0

Views: 83

Answers (0)

Related Questions