简体   繁体   中英

Proxying websocket with react-scripts does not work

I have a react web application and i use react-scripts for developpment. I use the proxy to proxy the requests and websockets to a backend.

My package.json :

{
  "name": "webapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    // ...
    "react-scripts": "^3.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    // ...
  },
  "devDependencies": {
    // ...
  },
  "homepage": "/home"
}

I have a setupProxy.js :

const proxy = require("http-proxy-middleware")

module.exports = app => {
  app.use(proxy('/api', {
    target: 'http://127.0.0.1:9140',
    ws: true
  }));

  app.disable('etag');
}

The proxy works fine for http request. The react web application perform a request on http://localhost:3000/api/foo/bar and the request is proxied on http://localhost:9140/api/foo/bar .

My issue is with websockets. The react web application open a websocket on ws://localhost:3000/api/foo/bar , the backend receive the websocket request and upgrade it and respond with a 101 http code. But the react web application never receive this response. The react web application receive a 400 http code response. So the websocket is closed.

I'm trying to find why the react application receive a 400 error. I tried many proxy configurations (i tried the proxy configuration in the package.json file, i tried some other possible configurations based on the http-proxy-middleware github page).

I found some issue with http-proxy-middleware and react-scripts :

After some investigation, it seems like the issue comes from sockjs-node used by Webpack. It looks like sockjs-node catch the request and replace my backend response with an error 400 response.

Does anyone know how to make websockets working with a proxy in a react application in developpment ?

In create-react-app v3.3.0 websocket proxying is broken . Try to downgrade to v3.2.0. I'm still on a v3.3.0 beta version as i depend on nullish coalescing, but i wouldn't generally recommend using a beta version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM