I have a node js API built with express. In one of my http endpoints, I would like to accept the request and send it over websockets to another server, and then return a reply. I'm using the ws library. The problem is that the websockets communication is not synchronous, so I don't know how to return an answer to the API client. Anyway, this is what I tried but it's not complete:
const express = require('express');
const app = express();
const WebSocket = require('ws');
const uuid = require('uuid');
const bodyParser = require('body-parser');
const ws = new WebSocket('ws://localhost:7465/');
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
ws.on('open', function open() {
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function incoming(data) {
console.log('Got data from server:');
console.log(data);
});
app.post('/my-http-endpoint', function (req, res) {
var payload = JSON.stringify({ body: req.body, requestID: uuid.v4() });
ws.send(Buffer.from(payload));
// How to send a reply?
})
app.listen(1337);