Why am I unable to send response object of Express through SocketIO?

ぃ、小莉子 提交于 2021-01-29 10:42:00

问题


I'm trying to send the response to an express request by sending it to a ws client and wait for its response. So I need to send the res object to the client (I couldn't find another way).

Here is what I did:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    socket.on('res', (e) => {
        e.res.send(e.data)
    })
})

app.get('/endpoint', (req, res) => {
    io.emit('req', { data: 'test', res: res });
});

http.listen(3000);

However, after going to /endpoint I'm getting this error:

RangeError: Maximum call stack size exceeded
at Function.isBuffer (buffer.js:428:36)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:42:87)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)
at hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:56:59)


回答1:


Why am I unable to send response object of Express through SocketIO?

When objects are sent through socket.io, they are converted to JSON using JSON.stringify() (or something similar). But JSON.stringify() has some requirements before it will work properly. In particular, it only supports certain data types and it does not support circular references and I'm guessing that you have issues with both of those in the res object.

It is not clear exactly what you're trying to accomplish here. There is literally no reason at all to send the res object to your client. Even if it could be stringified, there is nothing the client could do with that information anyway. It's just housekeeping information from your server in order to send a response from the server and that info can only be used by the server itself, not by a client.

If you want to send a message to a client and wait for the client's response, then socket.io has a feature to do that. It works by passing a callback as the 3rd argument to .emit() and then the client does something similar to craft its response. You can see the documentation for this socket.io "ack" feature here.



来源:https://stackoverflow.com/questions/50093188/why-am-i-unable-to-send-response-object-of-express-through-socketio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!