Received the error 'Headers cannot be set after they have been sent to the client' upon the second request

I created a web server that acts as a client-side application using socket.io-client and express. This setup is necessary for another project I am working on.

The web server emits the posted string and responds by sending the served string when it receives 'boom' emit from the io server.

Posting 'heat_bomb' works fine the first time, but when attempting a second time, an error '[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client' occurs at res.send(data) in socket.on().

Is there a way to refresh every time a post request is generated so that each request has an independent response?

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')
    })
})

Answer №1

In the /heat_bomb middleware, a new boom handler is registered for each request using the globally defined socket. Although it's not explicitly shown in your code snippet, it seems that triggering the emit('boom') during a second request invokes the original heat_bomb handler set during the first request, causing another res.send for the first request, which has already been completed. This results in the error message you are experiencing.

Simply relying on socket.once('boom') may not offer a reliable solution as one heat_bomb event could potentially override another, leading to inaccurate pairing of the data from one request with the res from another. For proper handling, consider passing the res as a secondary argument in your events, like this:


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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a website with an integrated, easy-to-use editing tool

Recently, I designed a website for a friend who isn't well-versed in HTML/CSS/JavaScript. He specifically requested that the site be custom made instead of using a web creator. Now, he needs to have the ability to make changes to the site without nee ...

Automated browsing: identifying the difference between AJAX and iframes

During my automated requests (scheduled at specific times, without user involvement), I have noticed that xmlHttpRequest includes extra http headers. In order for the server not to be able to distinguish these requests as automated (they should appear exa ...

What is the process for adding my JSON data to a select dropdown list?

Looking to populate a selectlist in HTML with options retrieved from an API. Below is the HTML code : <div id="example" role="application"> <div class="demo-section k-header"> <select id="FeaturesSelec ...

Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads <b>Filter Within Months:</b> <select class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change= ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Tips for embedding a script into an HTML document

I've been experimenting with tinymce npm and following their guide, but I've hit a roadblock. Including this line of code in the <head> of your HTML page is crucial: <script src="/path/to/tinymce.min.js"></script>. So, I place ...

What is the best method for implementing a file upload feature using jQuery and php?

Could someone explain how to create a jQuery multiple image upload feature (uploading without refreshing the page after choosing a file, only displaying the image but not inserting it into a database), and submit additional form data along with all images ...

Tips for retrieving data from a JSON response with the specified structure

When I make a request, the response is as follows: { "data": [ "http:\/\/www.domain.com.br\/anunciantes\/jorgediaz.y.com.r\/26\/img1.jpg", "http:\/\/www.domain.com.br\/anunciantes\/jorg ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

Tips for retrieving the selected option from a dropdown list using ReactJS

Currently, I am attempting to extract the value of a dropdown menu structured like this: <ul className="tabs" data-component={true}> <li> <section className="sort-list" data-component={true}> <select value={0} class ...

Identify the nested Object within the Json data

I am looking to add and name a nested object within my Json data structure. The current structure of my Json is as follows: { "MH": [ { "MHF46": "Ledig", "MHF60": "60", }, ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Error message: Node: TypeError - Attempted to access the 'sort' property of an undefined variable while using findOneAndUpdate() within a find() operation

My code snippet is shown below: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/school', function(err, db) { if (err) throw err; db.collection('students').find().toArray( ...

Cannot load JavaScript in Ajax tabs

I have implemented this ajax tabs on my website. However, the JavaScript code inside the content.htm file seems to be malfunctioning. Below is the code snippet I am using: Javascript $(document).ready(function(){ $("button").click(function(){ ...

Vue.js behaving abnormally due to certain circumstances

Currently, I am working on a vue application where I encountered some errors related to script execution on certain websites. By implementing the following code snippet, the issue is resolved: if ( window.location.href === 'chrome-extension:// ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

At times, Vue.js may encounter difficulties when attempting to load a component

Recently, a strange issue has been occurring in my production code. Although nothing has been changed, I am now receiving reports that occasionally a template fails to load causing the page to crash. I am currently using vue 2.16. The error messages being ...

Is it possible to directly connect to the MySQL service port using Node.js?

This computer is running on the Windows 7 operating system. It actually uses MariaDB, which is a fork of MySQL. The port being used is the default one, 3306. I am curious if there is a way to access this database system using JavaScript without requiring ...