Created by: dceddia
Added ws: true
to the httpProxyMiddleware options, and also listen
for the "upgrade" event so that websockets can be proxied immediately,
rather than waiting for an initial HTTP request.
How To Test This
I modified the template App.js
and added a componentDidMount
that creates a websocket. It tries to connect to localhost:3000, the webpack dev server.
componentDidMount() {
let s = new WebSocket("ws://localhost:3000/");
s.addEventListener('message', m => console.log(m.data));
s.addEventListener('error', m => console.log(m));
s.addEventListener('open', m => {
console.log(m);
s.send("hey there!");
});
}
Then, in packages/react-scripts/package.json
, added the proxy
option:
"proxy": "http://localhost:4000"
(it works with http
and with ws
-- no need for ws
though because of the ws: true
flag)
Finally, I set up a tiny Express echo server:
app.js
var app = require('express')();
var expressWs = require('express-ws')(app);
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send(msg);
});
});
app.listen(4000);
Package-wise it just needs npm install express express-ws
.
In one terminal, start up the WS server: node app.js
.
In another terminal, start up CRA: npm start
The browser console should show that the socket connected, and say "hey there!" The WS server terminal should also say "hey there!"
Still Works With Socket.io
I tested with socket.io as well -- that still works.
Express server: (npm install express socket.io
)
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on('msg', function (data) {
console.log(data);
});
});
server.listen(4000);
Same proxy settings.
In App.js
, import socket.io:
import io from 'socket.io-client';
Connect and send a message:
componentDidMount() {
let socket = io(`http://localhost:3000/`);
socket.emit('msg', "hey now!");
}
Install the client:
npm install socket.io-client
Start up the server and CRA, and the server terminal should print "hey now!"