【问题标题】:Why am I unable to send response object of Express through SocketIO?为什么我无法通过 SocketIO 发送 Express 的响应对象?
【发布时间】:2018-10-10 02:47:47
【问题描述】:

我正在尝试通过将响应发送到 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)

【问题讨论】:

    标签: javascript node.js express socket.io


    【解决方案1】:

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

    当通过 socket.io 发送对象时,它们会使用JSON.stringify()(或类似的东西)转换为 JSON。但是JSON.stringify() 有一些要求才能正常工作。特别是,它只支持某些数据类型,不支持循环引用,我猜你对 res 对象中的这两种类型都有问题。

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

    如果您想向客户端发送消息并等待客户端的响应,那么 socket.io 有一个功能可以做到这一点。它通过将回调作为第三个参数传递给.emit() 来工作,然后客户端执行类似的操作来制作其响应。您可以查看此 socket.io "ack" 功能的文档here

    【讨论】:

    • 知道了。这就是我想要实现的目标:stackoverflow.com/questions/50087400/…
    • 它只确认客户端已经收到。是否可以操作数据并作为 ack 发回?
    • @GijoVarghese - 是的,您可以发送数据,让客户端对其进行修改并将其作为 ack 发回。但是,您发送的数据必须只是数据,而不是实时的res 对象。因此,只需将您希望客户端修改的任何属性作为数据发送,然后让客户端发送回您的服务器可以使用的内容。如果你仔细查看文档示例,客户端可以使用 ack 发送回数据。
    • 好的。我试过了。但是出现错误“广播时不支持回调”
    • @GijoVarghese - 这是真的。您需要使用socket.emit(...) 发送给一个特定的客户,而不是所有客户。这也很有意义,因为您需要等待一个客户响应,而不是所有客户。
    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2019-12-30
    • 2019-03-10
    • 2021-09-10
    相关资源
    最近更新 更多