Issue with NodeJS SQL Login: Received error (ERR_HTTP_HEADERS_SENT): Headers cannot be set after being sent to the client

Hi there, I am fairly new to working with nodeJS and I have encountered an issue that I suspect lies within the second if statement inside "db.query..." in the code provided below. An error message showing

ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
keeps appearing but I'm not sure how to resolve it. My objective is to create a login form that retrieves data from mysql.

  app.post('/login',(req, res) =>{

        const { email, password } = req.body //pulls name="email" from html

        if(email && password){

            db.query('SELECT * from users WHERE email = ? ;',[email], function (err, result) {
                if (err) throw err;
                if (result) {
                    if(result[0].password === password){
                        req.session.userId = result[0].uid
                        return res.redirect('/home')
                    }
                }     
                console.log(result[0].email)
              });

        }
        res.redirect('/login')
    });

Answer №1

In order to ensure that your query is executed successfully before sending a response to the client, you should wait for the query execution to complete.

One way to achieve this is by modifying your code as shown below:

app.post('/login', async (req, res) =>{

    const { email, password } = req.body // retrieves the value of name="email" from HTML

    if(email && password){
        try {
          let result = await db.query('SELECT * from users WHERE email = ? ;',[email]);
          if (result) {
            if(result[0].password === password){
              req.session.userId = result[0].uid
              return res.redirect('/home')
            } else {
              res.redirect('/login')
            }
          }
       } catch(e) => {
         res.redirect('/login')
       }
   }
}

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

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

An error occurred when trying to pass JSON data to the view in the "orchard" framework: TypeError - e.slice is not a function

public ActionResult Grouping() { return View(); } public ActionResult Read([DataSourceRequest] DataSourceRequest request, string text) { var result = _auto.Table.ToList().Where(s => s. ...

The function socket.rooms returns an array with no elements

My server side code is as follows: io.on('connection', function (socket) { socket.join('main'); console.log(socket.rooms); /* ==> [] */ console.log(socket.adapter.rooms); /* ==> { '5incJ4hA4tKyJHUjAAAA&apo ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

The JavaScript setTimeout function not triggering repetitively for 10 instances

I'm facing an issue with a JavaScript/jQuery function that is designed to call itself multiple times if there is no available data. This is determined by making a web service call. However, the logging inside the web service indicates that it is only ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

Transforming a unirest 'GET' call into an axios request

I am currently utilizing TheRundown API to access sports data. The example provided to me makes use of unirest, but I am endeavoring to adapt that example into an axios request. While I have managed to make it work for the most part, my main challenge lies ...

Steps to configure the npm registry exclusively for a particular project

Currently, I am utilizing a private npm registry for one of my npm packages, while also referring to a couple of other packages from the default npm registry. The method I am currently employing involves setting the registry globally using the following co ...

Refresh information in AngularJS controller

I am currently working on a straightforward AngularJS script that is designed to retrieve data from a socket.io event and then integrate it into the ng template. Below is the JavaScript code I have written for this purpose: // Socket.io logic: var message ...

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Is it possible to run two Livescript (a fork of Coffeescript) applications using just one globally installed package?

I am currently using a modified version of Coffeescript called LiveScript for my application development. To execute files, I typically use the lsc command like this: $ lsc app.ls Recently, there was an update that changed the way modules are required. ...

A step-by-step guide on converting a JSON object to a CSV file using the json2csv nodejs module

I'm in the process of learning how to convert a JSON object into a CSV file using the json2csv node module. This is completely new to me as I have not worked with JSON previously. The structure of my JSON object is as follows: { "car": { ...

Converting Persian calendar date to Gregorian in JavaScript

Looking for assistance in converting a date from 1379/10/02 to AD format, specifically to the date 2000/4/29 using the momentJs library. Any help with this task would be greatly appreciated. Thank you! ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

Issue: Unable to locate the 'express' module while executing on Azure

I am encountering an issue with my node.js app while deploying it on Azure. It runs perfectly fine locally using express, but on Azure, I am getting the following error: Application has thrown an uncaught exception and is terminated: Error: Cannot find mo ...

How can we dynamically retrieve an image from the database in React in order to display it on the user interface?

I have a React front end with Node backend and I'm using sequelize for mySQL. Within my database, there is a table called "company" with a column named "logo" where images are stored. How can I dynamically generate a URL for the img tag in order to di ...

Tips for distinguishing between multiple submit buttons on a web page

while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<form action='./form_page.php' method='post'>"; echo "<td style='width:9%'>" . $row['studentID']."</td>"; echo "& ...

How would you execute a simple protractor test with the provided file hierarchy?

I have attempted to follow a tutorial located HERE for running protractor tests. Despite my efforts, I am facing an issue where the tests do not seem to run when I attempt to start them. While my webdriver-manager is functioning correctly, nothing seems to ...