繁体   English   中英

为什么我无法通过SocketIO发送Express的响应对象?

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

我正在尝试通过将其发送到ws客户端来发送对明确请求的响应,并等待其响应。 因此,我需要将res对象发送给客户端(我找不到其他方法)。

这是我所做的:

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);

但是,在转到/ endpoint后,我收到此错误:

RangeError:超出最大调用堆栈大小
在Function.isBuffer(buffer.js:428:36)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:42:87)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)

为什么我无法通过SocketIO发送Express的响应对象?

通过socket.io发送对象时,将使用JSON.stringify() (或类似方法)将它们转换为JSON。 但是JSON.stringify()在正常工作之前有一些要求。 特别是,它仅支持某些数据类型,不支持循环引用,并且我猜想您在res对象中都遇到了问题。

目前尚不清楚您要在这里完成什么。 实际上,根本没有理由将res对象发送给您的客户端。 即使可以将其字符串化,客户也无法处理该信息。 这只是服务器中的内部管理信息,以便从服务器发送响应,并且该信息只能由服务器本身使用,而不能由客户端使用。

如果要向客户端发送消息并等待客户端的响应,则socket.io具有执行此操作的功能。 它通过将回调作为第三个参数传递给.emit() ,然后客户端执行类似于其响应的操作。 您可以在此处查看此socket.io“ ack”功能的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM