What could be causing the error message "Error: Cannot modify headers after they are sent" to appear?

I am attempting to insert data into an MS SQL server when a JSON Data API POST request is made.

var express = require('express');
var app = express();
var sql = require('mssql');

// Connection string parameters.
var sqlConfig = {
    user: 'sa',
    password: 'Forward@123',
    server: '115.187.45.88',
    database: 'Example',
    requestTimeout: 1000,
    options: {
      "encrypt": false,
      "enableArithAbort": true
  }
}

// Initialize server and listen on http://localhost:8080/
var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("app listening at http://%s:%s/SendData", host, port)
});

app.use(
    express.urlencoded({
      extended: true
    })
  )
  
app.use(express.json())

app.post('/SendData', function (req, res) {

let data = '';
  req.on('data', chunk => {
    data += chunk;
  })
  
  req.on('end', () => {
    var obj=JSON.parse(data);
    for(var i=0;i<obj.length;i++){
        console.log(obj[i]);

        //write in db

        var sqlString="INSERT INTO [dbo].[EmpTable] ([id],[fname],[lname]) VALUES ("+obj[i].id+",'"+obj[i].fname+"','"+obj[i].lname+"')";
        console.log("sqlString ----- "+sqlString);
        executeQuery(res, sqlString);

    }
  })
    res.setHeader('Access-Control-Allow-Origin', '*');  
    return res.status(200).json({"Message":"Success!!!"});
    
});





var executeQuery = function(res,query){
    sql.connect(sqlConfig,function(err){
        if(err){
            console.log("there is a database connection error -> "+err);
            res.send(err);
        }
        else{
            // create request object
            var request = new sql.Request();

            // query to the database
            request.query(query,function(err,result){
                if(err){
                    console.log("error while querying database -> "+err);
                    res.send(err);
                }
                else{
                    res.send(result);
                    sql.close();
                }
            });
        }
    });
}

The following error message is being displayed:

_http_outgoing.js:491 throw new Error('Can't set headers after they are sent.');

Error: Can't set headers after they are sent. at validateHeader (_http_outgoing.js:491:11) at ServerResponse.setHeader (_http_outgoing.js:498:3) at ServerResponse.header (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:771:10) at ServerResponse.send (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:170:12) at ServerResponse.json (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:267:15) at ServerResponse.send (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:158:21) at E:\Node Workspace\node-post-api\post-api-db-write.js:80:25 at _query (E:\Node Workspace\node-post-api\node_modules\mssql\lib\base\request.js:420:9) at Request.tds.Request.err [as userCallback] (E:\Node Workspace\node-post-api\node_modules\mssql\lib\tedious\request.js:479:15) at Request.callback (E:\Node Workspace\node-post-api\node_modules\tedious\lib\request.js:56:14)

Answer №1

Whenever a message is sent to /SendData, the following response is returned:

res.setHeader('Access-Control-Allow-Origin', '*');  
return res.status(200).json({"Message":"Success!!!"});

This response is the only one that can be given for that specific request.

Additionally, you utilize executeQuery(res, sqlString) where you do the following:

res.send(result);

This action also provides the sole response that can be made to the request.

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

Running NPM install encounters difficulty when trying to access a private repository

npm login. I fill in my username, password, and email then successfully log in. I make a change to a package. After running npm publish, the (org) package is published, and I can view it on the NPM website when logged in. 5. However, attempting to install ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

What are the necessary steps to launch Next.js without relying on Vercel's platform?

Looking to deploy a Next.js app, but not on Vercel. What is the process for deploying it? In the past, I would drag and drop the build folder from React to the server, but with Next.js I am unsure of which files need to be deployed and how. Note: I am ut ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Do AJAX requests make Cross-site scripting attacks more significant?

Currently, I am in the process of developing a React application that utilizes a PHP (Codeigniter) backend. Despite Codeigniter not handling this issue automatically, I have taken it upon myself to delve into the matter. While I comprehend the importance ...

The div smoothly descended from the top of the page to the center under the control of jQuery

I am trying to implement a feature where a div slides down from the top of the page to the center when a button is clicked. However, my current code seems to be causing the div to slide from the bottom instead of the top. Ideally, I want the div to slide ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

ALERT: the SweeperThread task with process ID <pid> has been stalled for over two minutes

Encountering a peculiar issue when running a simple node process in a container, causing it to become defunct. Here is what shows up in the kernel log: Mar 21 19:07:08 ip-10-0-2-233 kernel: [26336450.745710] INFO: task v8:SweeperThrea:2569 blocked for mor ...

Create a universal function for executing a script within a node package on a worldwide scale

I am currently developing an npm package and I would like to have it execute its own command. Assuming my package is called hello-world and it contains a script named start in the package.json file that runs: node index.js My goal is to be able to type ...

Creating a global function in Node.js with Express.js---Would you like to learn how

I have an issue with making every first word capitalized in Node.js Express.js. Here is the function I am using: function titleCase(str) { var splitStr = str.toLowerCase().split(' '); for (var i = 0; i < splitStr.length; i++) { ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

Failure to use the appropriate root for ect.js is evident

After hastily putting together an express.js app, I decided to integrate ect into it. Despite following the instructions on the official website and GitHub page for ect, express keeps looking for files in the wrong location. My server.js file is set up as ...

Unable to verify credentials for accessing the MongoDB database on localhost

Recently, I embarked on a new project using Express and decided to utilize MongoDB as my database due to Node.js being the backend technology. This is my first time working with Mongo, and although I can authenticate successfully from the terminal, I' ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

Mongoose aggregate not returning any results

I'm currently working on using Mongoose aggregate to group businesses. I have a MongoDB script that is functioning properly. Below, you'll find the NodeJS code with Mongoose as well as the MongoDB code: History.aggregate() .cursor({ bat ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

Error: Unable to access the 'textContent' property of null - puppeteer

I've been delving into puppeteer lately and I'm quite enjoying it, but I keep encountering a particular issue. Is there a way to prevent this error from happening and retrieve the results of all non-null values? Sometimes this code functions corr ...