gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:59:40 28 4
gpt4 key购买 nike

我试图通过将响应发送到 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: 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)

最佳答案

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

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

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

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

关于javascript - 为什么我无法通过SocketIO发送Express的响应对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093188/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com