Search code examples
expresssocket.iocorsmicroservicesapi-gateway

Express proxy for socket.io


Running microservices architecture, I would like to forward all my socket.io traffic through my gateway to the socket.io microservice. My gateway is running express. My current implementation looks like this:

import proxy from 'http-proxy-middleware';
import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors())

// proxy middleware options
const options = {
    target: 'http://127.0.0.1:1234/test',
    changeOrigin: true,
    secure: false,
    ws: true
};

const exampleProxy = proxy(options);

app.use('/socket.io', exampleProxy);
app.use('/upgrade', exampleProxy);

app.listen(port);

The strange this is that the GET requests go through to my service, so I get the socket connection, but when trying to emit an event from the socket.io client (POST request), the request times out.

My express server logs, via morgan, the following in this case:

 [HPM] Error occurred while trying to proxy request /socket.io/?EIO=3&transport=polling&t=MrZfNeU&sid=cR-5g0531PU9XxiGAAAN from localhost:2999 to http://127.0.0.1:1234/test (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

My front-end displays cors error:

Access to XMLHttpRequest at 'http://localhost:8888/socket.io/?EIO=3&transport=polling&t=MrZfNeU&sid=cR-5g0531PU9XxiGAAAN' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When connecting directly to the socket.io server, it works perfectly. What could be the issue? Thanks!


Solution

  • Problem has been solved by placing the bodyParser below the proxy as mentioned in the following comment.