Express and Mongoose Server Crash resulted in an ERR_HTTP_HEADERS_SENT issue

Currently, I am developing a user authentication backend using express and mongoose.

My main focus right now is enabling users to update their name and email address.

To achieve this, I am implementing a system where the email input is cross-checked with the current user's email. If it doesn't match, then I verify if it matches any other user's email. If there is a match with another user, an error is thrown; otherwise, the new email is saved.

The process works smoothly for updating names and emails, except when a user already has the chosen username.

Upon encountering an error, both the error message is sent to the client and the server crashes with an "ERR_HTTP_HEADERS_SENT" error. Despite returning the error, I am unable to identify the root cause of this issue.

Below is the code snippet:

exports.update = (req, res) => {
  // Obtain New User Details
  const { firstName, lastName, email } = req.body;

  // Locate User
  User.findById(req.user._id, (err, user) => {
    if (err || !user) {
      return res.status(400).json({
        error: 'User not found.'
      });
    }
    user.firstName = firstName;
    user.lastName = lastName;

    // Check for Duplicate Email
    if (email !== user.email) {
      User.findOne({ email: email }).exec((err, existingUser) => {

        // Display Error Message if Duplicate Found
        if (!err && existingUser) {
          return res.status(400).json({
            error: "This email address is already in use.",
          });
        }

        // Send alert email to old address if no duplicate found.

      });

      // Update Email Address
      user.email = email;
    }

    // Save Updated User Information
    user.save((err, updatedUser) => {
      if (err) {
        console.log("Error: Could not update user.");
        return res.status(400).json({
          error: 'User update failed.'
        });
      }
      updatedUser.hashedPassword = undefined;
      updatedUser.salt = undefined;
      return res.json({
        message: 'Account updated successfully.',
        data: updatedUser
      });
    });
  });
};

Answer №1

Successfully resolved the issue:

// User Account Data Update
// ========================
exports.update = (req, res) => {
  // Retrieve New User Details
  const { firstName, lastName, email } = req.body;

  // Locate User
  User.findById(req.user._id, (err, user) => {
    if (err || !user) {
      return res.status(400).json({
        error: 'User not found.'
      });
    }

    if (email !== user.email) {
      User.findOne({ email: email }).exec((err, existingUser) => {

        // Display error message if email is already in use.
        if (!err && existingUser) {
          return res.status(400).json({
            error: "This email address is already in use.",
          });
        }

        // If not, send alert email to old address.

        // Finally, update user details.
        user.firstName = firstName;
        user.lastName = lastName;
        user.email = email;

        // Save Updated User Information
        user.save((err, updatedUser) => {
          if (err) {
            console.log("Error: Could not update user.");
            return res.status(400).json({
              error: 'User update failed.'
            });
          }
          updatedUser.hashedPassword = undefined;
          updatedUser.salt = undefined;
          return res.json({
            message: 'Account updated successfully.',
            data: updatedUser
          });
        });

      });
    } else {
      user.firstName = firstName;
      user.lastName = lastName;

      // Save Updated User Information
      user.save((err, updatedUser) => {
        if (err) {
          console.log("Error: Could not update user.");
          return res.status(400).json({
            error: 'User update failed.'
          });
        }
        updatedUser.hashedPassword = undefined;
        updatedUser.salt = undefined;
        return res.json({
          message: 'Account updated successfully.',
          data: updatedUser
        });
      });
    }
  });
};

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

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

Error [ERR_MODULE_NOT_FOUND]: Module could not be located in vscode

Issue with VS Code: Module Not Found Error View the image associated with the erroreN.png ...

Node Express app intercepts a POST request, increments a counter, and triggers an error after a certain threshold

In my project involving Node Express/Angular Civic, I am faced with the challenge of integrating it with a 3rd party API where each call incurs a cost of $1.00. While I am willing to cover some of the expenses, I want to implement a mechanism to halt the P ...

"Utilizing the mapSeries function in Node.js to asynchronously iterate over the

Using a list of keys, I attempted to retrieve all their corresponding values from redis with the following code: async.mapSeries(['offer', 'find'], function(seed) { client.smembers(string); }, function(err, resultArr) { err ...

node index of data that has been posted

My HTML file is quite straightforward: <form method="post" action="http://localhost:3000/post"> <input name="name" type="text"/><br /> <input name="last_name" type="text"/><br /> <button id="submit" type="submit"& ...

There was a hiccup encountered while trying to follow the steps for creating a

Despite others' attempts to solve the errors quickly, the search continues and the symptoms persist. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="046c6168686b29766165677044342a352a34">[email protected]< ...

What could be the reason for my npm package installed globally to not be able to utilize ts-node?

Recently, I've been working on developing a CLI tool for my personal use. This tool essentially parses the standard output generated by hcitool, which provides information about nearby bluetooth devices. If you're interested in checking out the ...

Exploring ways to locate files within node-inspector

As a newcomer to using node-inspector on Ubuntu, I am attempting to debug an Express application for the first time. Upon running the program and accessing http://0.0.0.0:8080/debug?port=5858 in Chromium or Google Chrome, all scripts load successfully in ...

Issues with error handling in ExpressJS arise frequently

In the server.js file, towards the very end, there is a block of code that appears to handle errors: app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFunction) { console.log(err); mongoDal ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...

Unable to set values to an array of objects in JavaScript

Currently, I am facing an issue in my node.js project where I am unable to assign values to an array of objects. This problem has occurred before, but I just can't seem to figure out the root cause. My suspicion is that it might be related to variable ...

NodeJS tutorial on obtaining the Instagram username and access token

How do I retrieve the username and access token after a user logs in using Instagram-passport for my app login? I'm having trouble accessing the 'profile' in the middleware section. //serialize user in the session passport.serializeUser(fun ...

What is the reason the server is not receiving the cookie?

I am currently running a nodejs express application on a server with two endpoints: POST /session - used to send back the cookie GET /resource - used to check if the cookie is sent back, returning 401 not found if it's not On the frontend, hosted on ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

Exploring the contents of a directory and accessing files in nodejs

Here is the current code snippet: const fs = require('fs') fs.readdir('C:\Users\Eva\Desktop\Main\Input', (err, files) => { if (err) { console.log(err); return; } files.forEach(file => { ...

Storing a reference to a user's login information

Struggling with establishing a straightforward relationship between User and Tweet Schemas. I've implemented a middleware to authenticate users based on their tokens upon login. The issue arises when it comes to saving a tweet for a logged-in user wit ...

Tips for executing npm/grunt commands within Jenkins

Hi everyone, I'm new to this area and currently facing a challenge with setting up Jenkins. I have been attempting to execute the following commands from Jenkins: npm install grunt quickStart As of now, I have Jenkins running on a Windows machine as ...

Troubleshooting issue with SQL delete statement - unable to delete a recipe with the specified recipe_id

Developing a functionality to delete data. I am currently working on removing a particular recipe by its unique identifier, which is the recipe_id. The issue I encountered is that when I send the request to delete using the handleDelete function in my bac ...

Upon adding data to mongodb, an error message is displayed stating "Cannot read property '_id' of undefined."

Backend Server-Side Code The following is my server-side code. Below it, you can find the client-side code along with the error that is being displayed. I am having trouble identifying what the issue might be. app.post("/service", async (res, re ...