Home > front end >  in Express JS , [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client , afte
in Express JS , [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client , afte

Time:12-07

This is my Route router.post("/create", isAdm ,tutorials.create); This is the conroller.js

exports.create = (req, res, bool) => {
  // Validate request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }
  else {
    if (bool) {
      let crypto = require('crypto');
      let hash = crypto.createHash('md5').update(req.body.password).digest('hex');
      console.log(req.body)
      // Create a User
      const user = new Users({
        username: req.body.username,
        password: hash,
        fullname: req.body.fullname
      });

      // Save Tutorial in the database
      Users.create(user, (err, data) => {
        if (err) {
          res.status(500).send({
            message:
              err.message || "Some error occurred while creating the User."
          });
        }
        else { res.send(data); }
      });
    }
    else{
      res.send("Unauthorized")
    }
  }
};

this is the model i'm Using

const User = function(user) {
  this.username = user.username;
  this.password = user.password;
  this.fullname = user.fullname;
};

User.create = (newUser, result) => {
  sql.query("INSERT INTO users SET ?", newUser, (err, res) => {
    if (err) {
      console.log("error: ", err);
      result(err, null);
      return;
    }

    console.log("created User: ", { id: res.insertId, ...newUser });
    result(null, { id: res.insertId, ...newUser });
  });
};

This is the isAdm middleware

const sqladminchecker = require("../db/index");
const JWTTOKEN = require('jsonwebtoken')
require('dotenv')
const isAdmin = (req, res, next) => {
    // Getting JWT from Cookies
    let jwtToken: string = ''
    let i: number
    try {

        let cookies = req.headers.cookie.split('; ')
        for (i = 0; i < cookies.length; i  ) {
            if (cookies[i].startsWith('jwt') != false) {
                jwtToken = cookies[i].split('=')[1]
            }
        }
        if (jwtToken != '') {
            const jwtData = JWTTOKEN.verify(jwtToken, process.env.JWT_SECRET)
            const { username, id } = jwtData
            // req.id = id
            sqladminchecker.query(
                "SELECT * FROM users WHERE id = ? AND isAdmin = ?",
                [id, 1],
                (err, reslt) => {
                    try {
                        if (!err) {
                            if (reslt.length == 1) {
                                next(true)
                            }
                            else {
                                console.log('else')
                                next(false)
                            }
                        }

                    }
                    catch {
                        console.log('catch')
                        next(false)

                    }
                }


            );


        }
        next()

    }
    catch {
        next(false)
    }
}
module.exports = isAdmin

this is the console error i'm getting

created User: { id: 15, username: 'dccdcdd', password: '0fac4fe563f30f5fa080216251074ad7', fullname: 'Minhazul Asif' } Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse.header (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/express/lib/response.js:771:10) at ServerResponse.send (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/express/lib/response.js:170:12) at ServerResponse.json (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/express/lib/response.js:267:15) at /home/fahimaloy/Desktop/Hospital_Project/backend/controller/user.controller.ts:29:24 at Query. (/home/fahimaloy/Desktop/Hospital_Project/backend/models/user.model.ts:19:5) at Query. (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/mysql/lib/Connection.js:526:10) at Query._callback (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/mysql/lib/Connection.js:488:16) at Query.Sequence.end (/home/fahimaloy/Desktop/Hospital_Project/backend/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24) { code: 'ERR_HTTP_HEADERS_SENT' }

this solves if I don't use the middleware "isAdm" what do I do?

CodePudding user response:

The controller code does not wait for the callback passed in User.create because you don't wait for its result. Use async/await to achieve that:

exports.create = async (req, res, bool) => {
...

     // Save Tutorial in the database
      try {
        // if Users.create supports callbacks only you always can wrap this with Promise
        const createdUser = await Users.create(user);
        res.send(createdUser);
      } catch (err) {
          res.status(500).send({
            message:
              err.message || "Some error occurred while creating the User."
          });
      }
  • Related