NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated.

router.route("/new").post((req, res) => {

  //Variable declarations
  sql.open(connectionString, function(err, conn){
    var pm = conn.procedureMgr();
    pm.callproc('dbo.AddRequestDetails',[request_zone,request_type,requester_type,request_flow,
      sales_order,requester_email,quotation,request_reason,request_status,
      StatusFlag, bot_status,bot_comments,additional_notification_to,additional_information, approver,
      old_value,new_value,new_shipping_point,partner_name,text_type,text_type_action,table_data], function(err,results,output){
      console.log("Hi");
        if (err != null) {
        console.log("error",err.message);
        var user =  req.ge('User');
        var scriptName = path.basename(__filename);
        var value = {err: err.message, user: user, scriptName:scriptName};
        axios.post(configData.SERVER_URL + "/api/logToDB", value);
        res.status(400).json(err.message);
      } else {
        console.log("Data successfully added in Main Table & Sub Table");
        res.json("Data successfully added in Main Table & Sub Table");
      }
      
    });
  });
});

module.exports = router;

This results in the following output:

Hi
Data successfully added in Main Table & Sub Table
POST /api/add/new 200 44.882 ms - 51
Hi
Data successfully added in Main Table & Sub Table
_http_outgoing.js:558
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they
are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (C:\Users\C572103\Documents\One
Order Change\OOC Portal\backend\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\express\lib\response.js:267:15)
    at C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\routes\uploadData.js:58:13
    at Object.callback (C:\Users\C572103\Documents\One Order
Change\OOC Portal\backend\node_modules\msnodesqlv8\lib\procedure.js:233:13)
    at onProcedureRaw (C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\msnodesqlv8\lib\procedure.js:60:22)
    at C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\msnodesqlv8\lib\reader.js:199:15
    at onStatementComplete (C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\msnodesqlv8\lib\driver.js:185:11)
    at Object.end (C:\Users\C572103\Documents\One Order Change\OOC Portal\backend\node_modules\msnodesqlv8\lib\driver.js:318:19) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

The SQL operations are being performed using msnodesqlv8

Answer №1

It appears that you are setting the response headers (such as res.setHeader(400)) after sending the response, causing issues with the if/else statements. It seems to be entering an error state after sending a 200 response.

Answer №2

Your code clearly shows that the function Hi is being called twice. It seems like you are opening a new SQL connection with sql.open, but failing to close it properly. This can result in the connection remaining open, causing unexpected behavior when handling multiple requests.

Additionally, make sure that each call to pm.callproc within a single request only performs one action and does not trigger two callbacks. Sending multiple responses for the same request is likely causing issues in your code.

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

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, { value: "CCT& ...

Trouble with npm installation while working within a corporate proxy network

Following the steps outlined below: Step1: Attempted to clone the AngularJS Tutorial repository using the command below git clone https://github.com/angular/angular-phonecat.git The repository was successfully cloned in C:\Git Due to operating beh ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

Encountering a Restangular error: "The 'then' function is not recognized" while attempting to resolve a promise

Welcome to my service. (function() { 'use strict'; angular .module('amazonScraperWebClient') .factory('dataService', dataService); /** @ngInject */ function dataService(Restangular) { Restangular.setBas ...

Tips for storing multiple pieces of text in HTML5 local storage

I have been working on creating functions and input boxes within a table to display data upon page reload. However, I am encountering difficulties in understanding how to store multiple inputs in local storage and then loop through them to show all the d ...

Mongoose not functioning correctly when attempting to remove items from an array that meet a certain condition

In my document, I have a property called weeks which is an Array containing Objects. [ { "time": [ "06", "00" ], "active": false, "reason": " ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

There was an issue encountered while attempting to add concurrently to the package.json

Bundle of scripts in package.json "scripts": { "begin": "node back-end/server.js", "serve": "nodemon back-end/server.js", "client-initiate": "npm start --prefix front-end", ...

Automatically return to the original URL after making a request

How can we dynamically return to the same page after a delete request is made? Request link: The request link that appears on multiple pages. <a href="/delete/id">delete</a> route.js router.get('/delete/:id', function (req, re ...

Using console.log() within a method while chaining in JavaScript/jQuery

I've been experimenting with developing jQuery plugins and I'm interested in chaining methods. The jQuery tutorial (found here: https://learn.jquery.com/plugins/basic-plugin-creation/) mentions that you can chain methods by adding return this; at ...

The application of Uglify to eliminate console logs can be inconsistent in its effectiveness

Having some trouble with my Vue3 app. I've implemented UglifyJS to remove console.logs in production environments, but it seems to be inconsistent. Sometimes it works fine, other times not so much. Every time I have to rebuild and hope for the best. I ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

MongoDB Node.js throws a RangeError when trying to push a message that exceeds the maximum call stack size

I'm currently delving into the world of building a MEAN app and encountering an issue when attempting to append a message to a messages array within my User Model. While I can successfully create a new message and pass the user object, I face an error ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

Organize nested level components in react native into a more structured order

Currently, I am working with some JSON data that has the following structure: const data = { "stores": [ { "name": "s1", "id": "6fbyYnnqUwAEqMmci0cowU", "customers": [ { "id": "4IhkvkCG9WWOykOG0SESWy", ...

Having issues with opening an exported Excel file using ExcelJS

While working on my JS project, I utilized the ExcelJS library. Everything was functioning smoothly with English characters. However, when I switched the language of my application to French and attempted to export the content as an Excel sheet, I encounte ...

Retrieve the average salary for every employee in the organization

I am new to learning PL/SQL and have no background in SQL. Recently, I have been experimenting with aggregate functions and wanted to find the average salary for each employee. My table looks like this: Original Table: https://i.sstatic.net/e7Fcl.png T ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Utilizing NodeJs to establish a seamless connection with elasticsearch

Recently, I have been exploring the option of updating my REST API to utilize elasticsearch. After some research, I came across the mongoosastic plugin, which appears to be a promising solution. However, I am having difficulty establishing a connection bet ...

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...