Home > Mobile >  My Server keeps crashing if User refreshes too much or Quick
My Server keeps crashing if User refreshes too much or Quick

Time:11-12

I'm at a loss and cant think of how to even google this.

I'm building a MERN fullstack app as my very first solo project. Someone told me it was too big (they were right) that I would get burned out (I am). Well, Jokes on them. They were right.

I have the server responding with a list of like, 4 users info from a database of like 4 users as a test. This is set up as a useEffect on the front end, not sure if that helps, people have told me it shouldnt have an effect on it.

it works only half the time, if not less than that. Other times the server crashes like my Dogecoin investment, saying I've already used res.send, which makes me want to throw my computer and monitors out my window and scare my neighbor downstairs, which wouldnt be as bad since shes nosy as hell and always comments on my mail and thinks shes my mail man.

Heres the Error on the Server Console

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:158:21)
    at /Users/apple/Documents/Web Dev/collab/Backend/routes/index.js:81:9
    at /Users/apple/Documents/Web Dev/collab/Backend/node_modules/mongoose/lib/model.js:5065:18
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
Emitted 'error' event on Function instance at:
    at /Users/apple/Documents/Web Dev/collab/Backend/node_modules/mongoose/lib/model.js:5067:15
    at processTicksAndRejections (internal/process/task_queues.js:75:11) {
  code: 'ERR_HTTP_HEADERS_SENT'

The route thats working about as often as my lazy Ex GF is the router.get(/users)

routes/index.js File

const router = require("express").Router();
const passport = require("passport");
const bodyParser = require("body-parser");
const genPassword = require("../lib/passwordUtils").genPassword;
const connection = require("../config/database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const isAuth = require("./authMiddleware").isAuth;
// cors is needed with router.use else you have to put routes on the app.js
const cors = require("cors");
router.use(cors({ origin: "http://localhost:3001", credentials: true }));
// const isAdmin = require("./authMiddleware").isAdmin;
router.use(bodyParser.urlencoded({ extended: false }));

/**
 * -------------- Post ROUTES ----------------
 *
 */

// router.post(
//   "/login",

//   passport.authenticate("local"),
//   (req, res) => {
//     console.log("working");
//     res.sendStatus(200);
//   }
// );
// router.post("/login", (req, res) => {
//   passport.authenticate("local", (err, user, info) => {
//     res.status(200);
//   });
// });
router.post("/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) throw err;
    if (!user) res.send("No User Exists");
    else {
      req.logIn(user, (err) => {
        if (err) throw err;
        res.send(user);
        return;
        console.log(req.user);
      });
    }
  })(req, res, next);
});

router.post("/register", (req, res) => {
  const saltHash = genPassword(req.body.repeatPassword);

  const salt = saltHash.salt;
  const hash = saltHash.hash;

  const newUser = new User({
    username: req.body.firstInput,
    fName: "",
    lName: "",
    title: "",
    hash: hash,
    salt: salt,
  });

  newUser.save().then((user) => {});
  res.sendStatus(200);
});

/**
 * -------------- GET ROUTES ----------------
 *
 */
router.get("/user", (req, res) => {
  res.send(req.user);
});
router.get("/users", (req, res) => {
  User.find({}, function (err, users) {
    const userMap = {};
    users.forEach(function (user) {
      userMap[user._id] = user;
    });
    res.send(userMap);
  });
});
router.post("/user", (req, res) => {
  const fName = req.body.firstInput;
  const lName = req.body.secondInput;

  const title = req.body.repeatPassword;

  const user = req.session.passport.user;
  User.updateOne(
    { _id: user },
    { fName: fName, lName: lName, title: title },
    function (err, result) {
      if (err) {
        res.sendStatus(401);
        console.log(err);
      } else {
        res.sendStatus(200);
      }
    }
  );
  // console.log(res.user);
});
router.get("/", isAuth);

// router.get("/logout", (req, res) => {
//   res.status(200);
//   req.logOut();
// });
// app.use((req, res) => {
//   User.findOne({ url: req.body.url })
//     .then((user) => {
//       if (!user) {
//         console.log("No user Found");
//         res.send("No user found");
//       } else {
//         console.log("user Found");
//         res.send(user).status(200);
//       }
//     })
//     .catch((err) => {
//       console.log(err);
//     });
// });
// function getUser(req, res, next) {
//   User.findOne({ url: req.body.url })
//     .then((user) => {
//       if (!user) {
//         console.log("No user Found");
//         res.status(401);
//         next();
//       } else {
//         console.log("success");
//         res.send({ user }).status(200);
//       }
//     })
//     .then((response) => console.log(response))

//     .catch((err) => {
//       console.log(err);
//     });
// }

// router.post("/visitor", getUser);

module.exports = router;

Here is the routes/authMiddleware File

  if (req.isAuthenticated()) {
    return res.status(200).json({ user: req.user, auth: true });
  } else {
    console.log("Nope");
    res.status(401).json({ auth: false });
  }
};

// module.exports.isAdmin = (req, res, next) => {
//     if (req.isAuthenticated() && req.user.admin) {
//         next();
//     } else {
//         res.status(401).json({ msg: 'You are not authorized to view this resource because you are not an admin.' });
//     }
// }

Heres the front End React if its needed. Its uglier than the truck my brother drives, but I'm new, so my mom wants you to cut me some slack.

import React, { useContext, useEffect } from "react";
// import { useHistory } from "react-router-dom";

import "./loggedStyles.css";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import SecondBoard from "../../QuestionBoard/secondBoard";
import { LoginContext, DialogueContext } from "../../../Context/context";

function Logged(props) {
  const { userInfo, setUserInfo } = useContext(LoginContext);
  const { openDialogue, setDialogue } = useContext(DialogueContext);

  const [fullWidth, setFullWidth] = React.useState(true);
  const [maxWidth, setMaxWidth] = React.useState("sm");
  useEffect(() => {
    if (userInfo.fName !== "") {
      setDialogue(false);
    } else {
      setDialogue(true);
    }
  }, [userInfo, setDialogue]);

  const closeDialogue = () => {
    setDialogue(true);
  };

  useEffect(() => {
    fetch("http://localhost:3000/user", {
      method: "GET",
      credentials: "include",
      withCredentials: true,

      headers: {
        "Content-Type": "application/json",
      },
    })
      .then(function (response) {
        if (!response.ok) {
          console.log(response.status);
          throw new Error("HTTP status "   response.status);
        } else {
          return response.json();
        }
      })
      .then((data) => {
        if (userInfo.fName === "") {
          setUserInfo({
            ...userInfo,
            id: data._id,
            fName: data.fName,
            lName: data.lName,
            title: data.title,
          });
        } else {
          return;
        }
      })
      .catch((err) => console.log(err));
  }, [userInfo, setUserInfo]);

  useEffect(() => {
    fetch("http://localhost:3000/users", {
      method: "GET",
      credentials: "include",
      withCredentials: true,

      headers: {
        "Content-Type": "application/json",
      },
    })
      .then(function (response) {
        if (!response.ok) {
          console.log(response.status);
          throw new Error("HTTP status "   response.status);
        } else {
          return response.json();
        }
      })
      .then((data) => {
        console.log(data);
      })

      .catch((err) => console.log(err));
  }, []);

  return [
    <div className="wrapper">
      <Dialog
        fullWidth={fullWidth}
        maxWidth={maxWidth}
        open={openDialogue}
        sx={{ border: "solid black" }}
      >
        <DialogContent sx={{ p: 0, borderRadius: "2vw" }}>
          <SecondBoard
            header="Basic Information"
            headerText="Fill in all Information"
            firstPlaceHolder="Enter your first name here"
            secondPlaceholder="Enter your last name here"
            thirdPlaceholder="Your Title (Job/Career)"
            passwordMatchClass="noDisplay"
            fetchRoute="user"
          />
        </DialogContent>
      </Dialog>

      <div className="section">
        <div className="top_navbar">
          <h4>DashBoard</h4>
        </div>
        <div className="container">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum
          dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
          incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
          quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
          velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
          occaecat cupidatat non proident, sunt in culpa qui officia deserunt
          mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur
          adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
          magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
          ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
          irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
          fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
          sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem
          ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
          veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
          ea commodo consequat. Duis aute irure dolor in reprehenderit in
          voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
          sint occaecat cupidatat non proident, sunt in culpa qui officia
          deserunt mollit anim id est laborum.
        </div>
      </div>
      <div className="sidebar">
        <div className="profile">
          <img
            src="https://1.bp.blogspot.com/-vhmWFWO2r8U/YLjr2A57toI/AAAAAAAACO4/0GBonlEZPmAiQW4uvkCTm5LvlJVd_-l_wCNcBGAsYHQ/s16000/team-1-2.jpg"
            alt="profile_picture"
          />
          <h3>
            {userInfo.fName} {userInfo.lName}
          </h3>
          <p>{userInfo.title}</p>
        </div>
        <ul>
          <li>
            <a href="/" className="active">
              <span className="icon">
                <i className="fas fa-home"></i>
              </span>
              <span className="item">Home</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-desktop"></i>
              </span>
              <span className="item">My Dashboard</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-user-friends"></i>
              </span>
              <span className="item">People</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-tachometer-alt"></i>
              </span>
              <span className="item">Perfomance</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-database"></i>
              </span>
              <span className="item">Development</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-chart-line"></i>
              </span>
              <span className="item">Reports</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-user-shield"></i>
              </span>
              <span className="item">Admin</span>
            </a>
          </li>
          <li>
            <a href="/">
              <span className="icon">
                <i className="fas fa-cog"></i>
              </span>
              <span className="item">Settings</span>
            </a>
          </li>
        </ul>
      </div>
    </div>,
  ];
}
export default Logged;

EDIT EDIT Just realized that I prematurely ejected my question before realizing that I should inform you that I had the Fetch for the /users in a useEffect until literally jsut recently as a last ditch effort to mess around and try to find out.

CodePudding user response:

To expand on the discussion in comments...

const isUser = (req, res, next) => {
  if (req.isAuthenticated()) {
    return res.status(200).json({ user: req.user, auth: true });
  } else {
    console.log("Nope");
    res.status(401).json({ auth: false });
  }
};

That auth middleware unconditionally sends a response, so any actual handler in a path where that middleware is used can't send another response.

The auth middleware should likely not send a response in the happy case, and should call next(), so the route gets called. This is explained very well in Express's docs.

CodePudding user response:

Probably not the cause, but this seems wrong, you probably meant to have curly brackets around res.send part.

if (!user) res.send("No User Exists");
else {
  req.logIn(user, (err) => {
    if (err) throw err;
    res.send(user);
    return;
    console.log(req.user);
  });
}
  • Related