将请求转发给 ws 客户端并等待响应 Express [英] Forward request to ws client and wait for response Express
问题描述
我正在尝试构建一个端点,该端点将接收请求,将请求数据发送到 WebSocket 客户端,等待事件,然后使用 express + socketio 发回响应.这个问题和它类似:Wait for socketio event inside express route
I'm trying to build an endpoint that will receive a request, emit the request data to a WebSocket client, wait for an event, then send back the response using express + socketio. This question is similar to it: Wait for socketio event inside express route
1) 在 http://localhost:3000/endpoint
2) 将事件作为 'req' 发送到网络套接字
2) Emit the event to web sockets as 'req'
3) 等待来自 ws 的 'res' 事件
3) Wait for 'res' event from ws
4) 发送接收到的事件详细信息作为 express 的响应.
4) Send the received events details as the response of express.
这是我的实现方式:
server.js
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');
});
var socket;
io.on('connection', function (s) {
socket = s;
});
http.listen(3000);
app.get('/endpoint', function (req, res) {
console.log('new request')
io.emit('req', { data: 'hello' });
socket.on('res', function (data) {
res.status(200).json(data);
});
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('req', (data) => {
console.log(data)
socket.emit('res', data);
});
</script>
该脚本对于 /endpoint
上的第一个请求工作正常.但是如果我再次点击网址,它会说
The script works fine for the first request on /endpoint
. But if i hit the url again, it says
错误 [ERR_HTTP_HEADERS_SENT]:发送后无法设置标头给客户
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
推荐答案
请注意:
socket.on('res', function (data) {
res.status(200).json(data);
});
每次套接字发送响应时都被调用,从而显示上述错误.您应该在回调函数内解除绑定侦听器.
Is being called each time a socket is sending a response, thus showing the above error. You should unbind the listener inside the callback function.
这篇关于将请求转发给 ws 客户端并等待响应 Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!