1

I created a react app with create-react-app, and tried to set up websocket proxy with http-proxy-middleware.

Here is the configure.

const { createProxyMiddleware } = require('http-proxy-middleware');
let remote_url = 'http://127.0.0.1:8088/';
module.exports = function (app) {
  app.use(
    '/name',
    createProxyMiddleware({
      target: remote_url,
      changeOrigin: false,
      ws: true,
      secure: false,
      //logLevel: 'debug',
      pathRewrite: {
        '^/name': '/name',
      },
    }),
  );
  app.use(
    '/api',
    createProxyMiddleware({
      target: remote_url,
      changeOrigin: false,
      ws: false,
      pathRewrite: {
        '^/api': '/api',
      },
    }),
  );
}

And this is the test script I put into browser's console to test

// Create WebSocket connection.
const socket = new WebSocket('ws://127.0.0.1:3000/name');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

When the web-dev-server starts, it prints the following log

[HPM] Proxy created: /  -> http://127.0.0.1:8088/
[HPM] Proxy rewrite rule created: "^/name" ~> "/name"
[HPM] Proxy created: /  -> http://127.0.0.1:8088/
[HPM] Proxy rewrite rule created: "^/api" ~> "/api"

The http proxy on /api works fine. However, the ws proxy on /name seems not working, and the connection just hangs for a while till it fails. The front-end project is started using CRA's web-dev-server, and the apis are served from a spring-boot project.

If I build the fronted project into the backend spring-boot project, and let the spring-boot project host all these static files. In this case, the websocket can connect, and the test script works fine.

lazyethan
  • 11
  • 2

0 Answers0