Home > Enterprise >  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - How to solve i
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - How to solve i

Time:04-29

It show error json in postman as expected but after that it crashed.

  • It not get crashed after sending success json

DB connected POST /api/signup 200 84.443 ms - 27 events.js:377 throw er; // Unhandled 'error' event ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (internal/errors.js:322:7)
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:278:15)
at /home/aman/Projects/Discover/discover_blog/backend/controllers/auth.js:22:30
at /home/aman/Projects/Discover/discover_blog/backend/node_modules/mongoose/lib/model.js:5004:18
at processTicksAndRejections (internal/process/task_queues.js:77:11)

Emitted 'error' event on Function instance at: at /home/aman/Projects/Discover/discover_blog/backend/node_modules/mongoose/lib/model.js:5006:15 at processTicksAndRejections (internal/process/task_queues.js:77:11) { code: 'ERR_HTTP_HEADERS_SENT' }

//

const User = require("../models/user");
const shortId = require("shortid");
//
const signup = (req, res) => {
  const { name, email, password } = req.body;
  User.findOne({ email: email }).exec((err, user) => {
    if (user) {
      return res.status(400).json({
        error: "Email is taken ",
      });
    }
  });

  let username = shortId.generate();
  let profile = `${process.env.CLIENT_URL}/profile/${username}`;
  let newUser = new User({ name, email, password, profile, username });

  newUser.save((err, user) => {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    return res.json({
      message: "Signup is successfull! Please signin",
      user: user,
    });
  });
};

module.exports = { signup };

CodePudding user response:

You're running newUser.save too early - you need to wait until .findOne finishes, otherwise you're both sending the initial 400 status (that the email is taken) and then one with the signup results. I'd also recommend not ignoring the possible .findOne error.

const signup = (req, res) => {
    const { name, email, password } = req.body;
    User.findOne({ email: email }).exec((err, user) => {
        if (err) {
            return res.status(400).json({
                error: err,
            });
        }
        if (user) {
            return res.status(400).json({
                error: "Email is taken ",
            });
        }
        const username = shortId.generate();
        const profile = `${process.env.CLIENT_URL}/profile/${username}`;
        const newUser = new User({ name, email, password, profile, username });

        newUser.save((err, user) => {
            if (err) {
                return res.status(400).json({
                    error: err,
                });
            }
            return res.json({
                message: "Signup is successfull! Please signin",
                user: user,
            });
        });
    });
};
  • Related