'Cannot set headers after they are sent to the client' 第二次请求后

'Cannot set headers after they are sent to the client' after second request

我使用 socket.io-client 和 express 创建了一个作为客户端的网络服务器(因为我必须在其他项目中使用这种形式)。

它发出字符串 posted,当接收到来自 io 服务器的 'boom' 发出时,它通过发送所服务的字符串进行响应。

第一次发布 'heat_bomb' 时效果很好,但是当我第二次尝试时,出现在 res.send(数据)在 socket.on().

有没有办法在每次产生post请求时刷新,让每个请求都使用独立的响应?

app.ts

import express from 'express'
import {io} from 'socket.io-client'
import bodyParser from 'body-parser'

const app=express()
const PORT=8080

const socket=io(`http://localhost:2002`, {
    query:{
        hello:"merhaba"
    }
})

app.use(bodyParser.urlencoded({extended:false}))

app.get('/', (req, res)=>{
    res.sendFile(__dirname+`/index.html`)
})
app.post('/heat_bomb', (req, res)=>{
    socket.emit('heat_bomb', req.body.elem)
    socket.on('boom', (data)=>{
        res.send(data)
    })
})

app.listen(PORT, ()=>{
    console.log(`Server Running: ${PORT}`)
})

index.html

$('#heat_button').click(function(){
    console.log('heating bomb')
    $.post('/heat_bomb', {elem: $('#input_number').val()},(data, status)=>{
        console.log(data)
        console.log('heated')
    })
})

您的 /heat_bomb 中间件为同一全局定义的 socket 上的每个请求注册一个新的 boom 处理程序。尽管您的代码片段没有显示 heat_bombboom 事件是如何连接的,但我假设第二个请求期间的 emit('boom') 重新触发了已注册的 heat_bomb 处理程序在第一个请求期间,导致第一个请求的 res 的另一个 res.send,该请求已经完成。这导致观察到的错误消息。

socket.once('boom') 本身并不能可靠地解决这个问题:如果一个 heat_bomb 事件可以超越另一个,则第一个 data 可能会错误地与 [=19= “配对” ] 从第二。 res 需要成为事件的第二个参数,如下所示:

socket.emit('heat_bomb', req.body.elem, res);
socket.once('boom', function(data, res) {
  res.send(data);
});