Home > Mobile >  Why I am getting : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clie
Why I am getting : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clie

Time:11-05

I am working on a blog website with multi-role admins. Everything was working fine before I add a middleware to check and prevent an admin from accessing the login page while logged in or preventing any admin page before logging in. I am getting this error whenever I try to access the login page while logged in or any page inside the protected admin page before logging in. Below I have attached my code.

Admin Route JS :

const adminController = require("../controllers/adminController");
const adminAuth = require("../middlewares/adminAuth");

// Register new admin
adminRouter.get("/register", adminAuth.isLogin, adminController.register);
adminRouter.post("/register", adminController.registerSave);

// Login
adminRouter.get("/login", adminAuth.isLogout, adminController.login);
adminRouter.post("/login", adminController.loginSave);

// Logout
adminRouter.get("/logout", adminAuth.isLogin, adminController.logOut);

// Other pages
adminRouter.get("/dashboard", adminAuth.isLogin, adminController.dashboard);
adminRouter.get("/all-admin", adminAuth.isLogin, adminController.allAdmin);
adminRouter.get("/all-post", adminAuth.isLogin, adminController.allPost);

Admin Controller JS

const login = async (req, res) => {
  res.render("admin/login", { title: "Log in" });
};
const loginSave = async (req, res) => {
  try {
    const email = req.body.adminEmail;
    const password = req.body.adminPassword;

    const adminEmailFind = await adminUser.findOne({ email: email });

    if (adminEmailFind) {
      const adminPassMatch = await bcrypt.compare(
        password,
        adminEmailFind.password
      );

      if (adminPassMatch) {
        req.session.user_id = adminEmailFind._id;
        req.session.isSuperAdmin = adminEmailFind.isSuperAdmin;
        req.session.isAdmin = adminEmailFind.isAdmin;

        if (adminEmailFind.isSuperAdmin == 1) {
          res.redirect("/admin/dashboard");
        } else if (adminEmailFind.isSuperAdmin == 0 && userData.isAdmin == 1) {
          res.redirect("/admin/dashboard");
        } else {
          res.render("admin/login", {
            title: "Login",
            statusColor: "#ef4444",
            message: "Sorry !! Admins can proceed only",
          });
        }
      } else {
        res.render("admin/login", {
          title: "Login",
          statusColor: "#ef4444",
          message: "Email or Password does not match !!!",
        });
      }
    } else {
      res.render("admin/login", {
        title: "Login",
        statusColor: "#ef4444",
        message: "Email could not be found !!!",
      });
    }
  } catch (error) {
    console.log(error.message);
  }
};

const dashboard = async (req, res) => {
  res.render("admin/index", { title: "Dashboard" });
};

Admin Auth middleware

const isLogin = async (req, res, next) => {
  try {
    if (
      !req.session.user_id &&
      !req.session.isSuperAdmin &&
      !req.session.isAdmin
    ) {
      res.redirect("/admin/login");
    }
    next();
  } catch (error) {
    console.log(error.message);
  }
};
const isLogout = async (req, res, next) => {
  try {
    if (
      req.session.user_id &&
      req.session.isSuperAdmin &&
      req.session.isAdmin
    ) {
      res.redirect("/admin/dashboard");
    }
    next();
  } catch (error) {
    console.log(error.message);
  }
};

module.exports = { isLogin, isLogout };

CodePudding user response:

Problem

You are calling next after redirect

Solution

Add return before or after res.redirect();

return res.redirect("/admin/login");

or

res.redirect("/admin/login");
return

Example:

const isLogin = async (req, res, next) => {
  try {
    if (
      !req.session.user_id &&
      !req.session.isSuperAdmin &&
      !req.session.isAdmin
    ) {
      return res.redirect("/admin/login");
    }
    next();
  } catch (error) {
    console.log(error.message);
  }
};
  • Related