I’m trying to build a very basic HTTP proxy using node.js. The purpose is that I can read all websocket messages sent between front-end and back-end and process them somewhere.
This is my code:
var http = require('http')
var httpProxy = require('http-proxy');
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 8123
}
});
var proxyServer = http.createServer(function (req, res) {
console.log("Request Received");
proxy.web(req, res);
});
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
console.log("WS Upgrade Request Received");
proxy.ws(req, socket, head);
socket.on('data', function(data) {
console.log('Data sent through WebSocket:', Buffer.from(data).toString());
console.log('Data sent through WebSocket (JSON):', JSON.stringify(data, true, 2));
console.log('Data represented as data to string: ', data.toString());
// exception thrown
//console.log('Data through JSON.parse(): ', JSON.parse(data));
// exception thrown
//console.log('Data represented as buffer: ', JSON.parse(Buffer.from(data)).toString());
});
});
The problem is that it looks like the data I’m capturing here through the above function is not JSON decoded.
This is an example of output I’m getting:
Data sent through WebSocket: ��F��
Data sent through WebSocket (JSON): {
"type": "Buffer",
"data": [
138,
128,
31,
70,
156,
143
]
}
Data represented as data to string: ��F��
Do I need to do something extra to get the JSON format from the websocket?