我正在尝试通过将响应发送到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)
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)
在hasBinary(/workspace/socketio/node_modules/has-binary2/index.js:56:59)
答案 0 :(得分:1)
为什么我无法通过SocketIO发送Express的响应对象?
当通过socket.io发送对象时,它们将使用JSON.stringify()
(或类似的东西)转换为JSON。但是JSON.stringify()
在它正常工作之前有一些要求。特别是,它只支持某些数据类型,它不支持循环引用,我猜你在res
对象中都存在问题。
目前尚不清楚你要在这里完成什么。根本没有理由将res
对象发送给您的客户端。即使它可以被字符串化,客户也无法对该信息做任何事情。它只是来自服务器的内务处理信息,以便从服务器发送响应,该信息只能由服务器本身使用,而不能由客户端使用。
如果要向客户端发送消息并等待客户端的响应,则socket.io具有执行此操作的功能。它的工作原理是将一个回调作为第三个参数传递给.emit()
,然后客户端做类似的事情来制作它的响应。您可以看到此socket.io“ack”功能here的文档。