将请求转发到ws客户端并等待响应Express [英] Forward request to ws client and wait for response Express

查看:192
本文介绍了将请求转发到ws客户端并等待响应Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个端点,该端点将接收请求,将请求数据发送到WebSocket客户端,等待事件,然后使用express + socketio发送回响应.这个问题与此类似:等待快递路线中的socketio事件

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"发送到Web套接字

2) Emit the event to web sockets as 'req'

3)等待来自WS的"res"事件

3) Wait for 'res' event from ws

4)发送收到的事件详细信息作为快速响应.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆