NodeJs - Issue: Headers cannot be changed once they are sent & TypeError: req.next is undefined

My goal is to retrieve data from a MySQL database by calling methods to insert and read information. The reason I am doing this is because node.js operates asynchronously. Here is my code:

exports.list = function(req, res){

  var moduleRows;

  req.getConnection(function(err,connection){
        var query = connection.query('SELECT * FROM questions WHERE module_id = ?',[X],function(err,rows)
        {
            for(var i = 0;i < rows.length;i++){
                moduleRows = rows[i];
                GetResults(moduleRows); 
            }
        });

        var GetResults = function(moduleRows) {
            var RightAnswer = 0;
            var WrongAnswer1 = 0;
            var query = connection.query("SELECT * FROM studentsanswers WHERE Question = '"+moduleRows.question+"' ",function(err,rows2)
            {
                    for(var ii = 0;ii < rows2.length;ii++){
                        if (rows2[ii].Answer == moduleRows.RightAnswer){
                            RightAnswer++;
                        }
                        else if (rows2[ii].Answer == moduleRows.WrongAnswer1){
                            WrongAnswer1++;
                        }
                    }
                var Data = {
                    question: moduleRows.question,
                    RightAnswer: moduleRows.RightAnswer,
                    WrongAnswer1: moduleRows.WrongAnswer1,
                    NumberOfRightAnswer: RightAnswer,
                    NumberOfWrongAnswer1 : WrongAnswer1
                };
                insertResults(Data);
                return;
            });
        }

        var insertResults = function(Data) {
            var query = connection.query("INSERT INTO statistics set ? ",Data, function(err, rows)
                {   
                    PrintResults();
                    return;
                });
        }

        var PrintResults = function() {
            var query = connection.query("SELECT * FROM statistics" ,function(err,rows)
            {
                res.render('StatisticsByModules',{page_title:"Questions - Node.js",data:rows});
                return;
            }); 
        }
    });

};

I'm encountering the following errors: Error: Can't set headers after they are sent. TypeError: req.next is not a function

Answer №1

Within the code snippet below, there are repeated calls to GetResults(moduleRows) and PrintResults, resulting in multiple invocations of res.render within the PrintResults method. This approach is not efficient as it sends render requests multiple times for a single request. To improve this, you should first create a data list and then call req.render once with the queried data.

var query = connection.query('SELECT * FROM questions WHERE module_id = ?', [X], function (err, rows) {
    for (var i = 0; i < rows.length; i++) { // <== HERE
        moduleRows = rows[i];
        GetResults(moduleRows);
    }
});

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

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Utilizing custom form fields with JavaScript in Symfony2

Here is my form field template: {% block test_question_widget %} {% spaceless %} <div {{ block('widget_container_attributes') }}> {% set type = type|default('hidden') %} <input type="{{ typ ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Eliminating a particular tag along with its corresponding text - cheeriojs

Is there a way for me to remove a particular tag and its content from the HTML file I am scraping? I need help in searching for and deleting this specific tag and text altogether. <p class="align-left">&#xA0; Scheduled Arrival Time</p> ...

Transmit the image created with node-gd to the recipient

UPDATE: here is the solution that worked for me res.set('Content-Type', 'image/png'); res.end(data, 'binary'). I have been experimenting with generating images dynamically using node-gd in my node.js/express application. Th ...

Leveraging NPM and MYSQL to transfer query outcomes to a different variable

I'm in need of assistance with a database package I'm developing for a larger application. The goal is to store specific data in a database using the mysql package in npm. However, I'm encountering an issue where the results variable always ...

Utilize the sortable script for dynamically loaded items via AJAX

For the drag and drop feature on my website, I am using jQuery sortable. I have a button that displays results with items on the screen. These items can be dragged and dropped into various sections. The issue I'm facing is that if I include the sort ...

The speed of npm installation leaves much to be desired

This is the content of my package.json file: { "name": "trainologic", "version": "1.0.0", "description": "", "main": "main.js", "dependencies": { "child_process": "^1.0.2", "http-server": "^0.9.0", "open": "0.0.5" }, "devDepende ...

When trying to locate an item in an array within a VUE application, it may result in

I've got this code snippet that successfully finds the item details in an array: var findGroupId = medias.find(medias => medias.group_name === this.groupName) The medias variable is an array. When I run console.log(findGroupId), I get this result ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

Issue with video not displaying in EJS template on node.js server

I have successfully uploaded a video using a node.js server and saved the FilePath to MongoDB in my /public/uploads folder. Within my ejs file, I am trying to display videos using the following code snippet: //Videos is an array of objects retrieved from ...

Reactivate IntelliJ IDEA's notification for running npm install even if you have previously selected "do not show again" option

One of the great features in Intellij IDEA is that it prompts you with a notification when the package.json has been changed, asking if it should run npm install, or whichever package manager you use. I have enjoyed using this feature for many years. Howe ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

AngularJS: Understanding the difference between ng-show and using display:none

I recently encountered a scenario where I needed to hide an HTML element by default using CSS. Here's how I did it: HTML: <div class="box"> </div> CSS: .box { display: none; } However, I wanted to be able to show and hide the elem ...

Setting up a Node application on a server with the help of Apache, npm, and pm

            I recently deployed a Node.js application (myapp.js) on a server with a specific IP address. The installation and startup process using npm went smoothly this time around, unlike past experiences with Apache which were much more complic ...

Incorporating a personalized image to create custom icons on the Material UI bottom navigation bar

Is it possible to replace the default icon with a custom image in material ui's BottomNavigation component? I'm curious if Material UI supports this feature. If you'd like to take a closer look, here is the link to the codesandbox. ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...