I am trying to return some data to my react frontend from my moleculer backend upon connection over sockets. I am running into challenges in getting the data, and what's particularly confusing to me is, when I have an error on the backend, that full error gets returned over the socket to the front-end. But when I resolve the error, all I get on the front-end is null
. I am unclear why I am getting a response in the error case, and a null
response when there is no error. Any help would be greatly appreciated.
This is my code on the backend. This function fires when the socket request for 'auth.register' comes in:
register(ctx) {
const socketId = ctx.meta.socket.id;
console.log('socketId: ', socketId);
const response = {
status: 'success',
code: null,
message: 'Device registered with version 1.0.0.',
body: { socketId },
broadcast: false,
messageId: 'unknown',
opts: {}
}
return response;
},
And this is my front-end socket call:
io.Socket.on('connect', () => {
console.log("Connection with the socket gateway established on socket");
// register
io.Socket.emit('call', 'auth.register', {
key: config.key,
version: `${config.app} ${config.version}`,
app: config.app,
}, (res) => {
console.log('res: ', res);
});
});
With the code like this, res
in the console on the front-end is equal to null
.
Now, if I change the backend code to have an error, like so:
register(ctx) {
const socketId = ctx.meta.socket.id;
console.log('socketId: ', socketId);
response = {
status: 'success',
code: null,
message: 'Device registered with version 1.0.0.',
body: { socketId },
broadcast: false,
messageId: 'unknown',
opts: {}
}
return response;
},
The full error gets returned over the socket, so in the front-end console, res
is this:
{name: "ReferenceError", message: "response is not defined"}
I'm trying to understand why, if there is an error on the backend, that gets successfully returned in the callback of the socket call from the front-end, but if there is no error all I end up with is null
.
What am I missing here? How can I return the data to the front-end in this situation?