javascript - 为什么我无法通过 SocketIO 发送 Express 的响应对象?
问题描述
我正在尝试通过将响应发送到 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:在 hasBinary (/workspace/socketio/node_modules/has-binary2/index.js:42:87) 处 hasBinary (/workspace/socketio/ )
处的 Function.isBuffer (buffer.js:428:36)超出了最大调用堆栈大小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”功能的文档。
推荐阅读
- java - 有没有办法在 Android 中创建一个泛型类的片段?
- c# - Aws lambda 代理 Swagger 模板集成
- python - 如何在 Google Directory API 中正确使用“下一页令牌”
- list - Prolog没有以我想要/需要的方式显示输出
- google-bigquery - 带有目标表 vrs 插入语句的 bq 查询
- c# - .Net Core Connected Services - 共享类型
- java - 为什么两个 LocalDate 变量之间的比较不起作用?
- c# - 如何使用反序列化对象 c#
- c - 如何显示C中输入的总和和计算
- charts - 如何在颤动中制作动态图表?