Node.js 将SSE与NodeJ一起使用时出现多个http请求

Node.js 将SSE与NodeJ一起使用时出现多个http请求,node.js,http,server-sent-events,Node.js,Http,Server Sent Events,我正在尝试实现一个应用程序,我需要做的一件事是使用服务器发送的事件将数据从服务器发送到客户端。SSE的基础是建立一个连接,在该连接中,数据在不关闭该连接的情况下来回传输。我现在遇到的问题是,每次我使用EventSource()从客户端发出HTTP时,都会发出多个请求 客户: const eventSource = new EventSource('http://localhost:8000/update?nick='+username+'&game='+gameId) eventSo

我正在尝试实现一个应用程序,我需要做的一件事是使用服务器发送的事件将数据从服务器发送到客户端。SSE的基础是建立一个连接,在该连接中,数据在不关闭该连接的情况下来回传输。我现在遇到的问题是,每次我使用
EventSource()
从客户端发出HTTP时,都会发出多个请求

客户:

 const eventSource = new EventSource('http://localhost:8000/update?nick='+username+'&game='+gameId)
 eventSource.onmessage = function(event) {
        const data = JSON.parse(event.data)
        console.log(data)
 }       
服务器(Node.Js):

这是我在chrome开发工具中看到的。当客户端尝试使用SSE连接时,它会向服务器发出多个请求。然而,本应只提出一项请求


你们有谁知道怎么解决这个问题吗?提前谢谢。

这样做的方法是不包括
res.end()
,因为连接必须保持活动状态。除此之外,我还必须跟踪用户发出的http请求的响应,因此我使用以下方法创建了一个不同的模块:

let responses = []

module.exports.remember = function(res){
    responses.push(res)
}

module.exports.forget = function(res){
    let pos = responses.findIndex((response)=>response===res)
    if(pos>-1){
        responses.splice(pos, 1)
    }
}

module.exports.update = function(data){
    for(let response of responses){
        response.write(`data: ${data} \n\n`) 
    }
}

这样可以访问响应对象并使用函数
update()
向连接的客户端发送数据。

这样做的方法是不包括
res.end()
,因为连接必须保持活动状态。除此之外,我还必须跟踪用户发出的http请求的响应,因此我使用以下方法创建了一个不同的模块:

let responses = []

module.exports.remember = function(res){
    responses.push(res)
}

module.exports.forget = function(res){
    let pos = responses.findIndex((response)=>response===res)
    if(pos>-1){
        responses.splice(pos, 1)
    }
}

module.exports.update = function(data){
    for(let response of responses){
        response.write(`data: ${data} \n\n`) 
    }
}
通过这种方式,用户可以访问响应对象,并使用函数
update()
向连接的客户端发送数据