Express router not routing to correct route

I have 3 separate files for student ,teacher and admin routing and used them in server.js file as general middleware using the use method. when I route with axios .post("http://localhost:5000/student/login", user) in the frontend with react it keeps diverting to admin route. I do not get it? does the middleware I have defined wrong or what? the server console saying TypeError: Cannot read properties of null (reading 'email') at C:\Users\ayex\Desktop\freecodecamp\AASTUweb\server\routes\adminRoutes.js:147:32

server.js

require("dotenv").config();
const express = require("express");
const app = express();
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo");
const cors = require("cors");

app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: MongoStore.create({
      mongoUrl: process.env.DB,
      collection: "sessions",
    }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 3 },
  })
);

app.use(passport.initialize());
app.use(passport.session());

mongoose
  .connect(process.env.DB)
  .then(() => {
    console.log("DB connection successful");
  })
  .catch((err) => {
    console.log(`DB connection Error: ${err}`);
  });

  const teacherRouter = require("./routes/teacherRoutes");
  const studentRouter = require("./routes/studentRoutes");
  const adminRouter = require("./routes/adminRoutes");

  app.use("/teacher", teacherRouter);
  app.use("/admin", adminRouter);
  app.use("/student", studentRouter);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`server is running on port ${PORT}`);
});

module.exports = app;

adminRoutes.js

const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");

const Admin = require("../models/adminModel.js");

router.route("/register").post(
  (req, res, next) => {
    Admin.findOne({ fullName: req.body.fullName }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.json({ user: "user with that name already exists!" });
      } else {
        const {
          fullName,
          email,
          phoneNumber,
          password,
        } = req.body;
        const hash = bcrypt.hashSync(password, 12);
        console.log(hash);
        const newUser = new User({
          fullName,
          email,
          phoneNumber,
          password: hash,
        });
        newUser.save((err, data) => {
          if (err) console.log(err);
          next(null, data);
        });
      }
    });
  },
  passport.authenticate("local", { failureRedirect: "/" }),
  (req, res, next) => {
    const userAuth = req.user.fullName;
    Admin.findOne({ fullName: userAuth }, (err, user) => {
      if (err) console.log(err);
      res.json({ user: user.fullName });
    });
  }
);

router.route("/login").post(passport.authenticate("local"), (req, res) => {
  const userAuth = req.user.fullName;
  if (userAuth) {
    Admin.findOne({ fullName: userAuth }, (err, user) => {
      if (err) console.log(err);
      res.json({ user: user.fullName });
    });
  } else {
    res.statusCode(401).json({ user: "Incorrect password or email" });
  }
});

passport.serializeUser((user, done) => {
  done(null, user._id);
});

passport.deserializeUser((id, done) => {
    Admin.findOne({ _id: new ObjectID(id) }, (err, doc) => {
    done(null, doc);
  });
});

const customFields = {
  usernameField: "email",
};

passport.use(
  new LocalStrategy(customFields, (email, password, done) => {
    Admin.findOne({ email }, (err, user) => {
      console.log(`User ${user.email} attempted to log in.`);
      if (err) return done(err);
      if (!user) return done(null, false);
      if (!bcrypt.compareSync(password, user.password)) {
        return done(null, false);
      }
      return done(null, user);
    });
  })
);

module.exports = router;

studentRoutes.js

const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");
const crypto = require("crypto");

const User = require("../models/studentModel.js");

router.route("/register").post(
  (req, res, next) => {
    User.findOne({ fullName: req.body.fullName }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.json({ user: "user with that name already exists!" });
      } else {
        const {
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password,
        } = req.body;
        const hash = bcrypt.hashSync(password, 12);
        console.log(hash);
        const newUser = new User({
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password: hash,
        });
        newUser.save((err, data) => {
          if (err) console.log(err);
          next(null, data);
        });
      }
    });
  },
  passport.authenticate("local", { failureRedirect: "/" }),
  (req, res, next) => {
    const userAuth = req.user.fullName;
    User.findOne({ fullName: userAuth }, (err, user) => {
      if (err) console.log(err);
      res.json({ user: user.fullName });
    });
  }
);

router.route("/login").post(passport.authenticate("local"), (req, res) => {
  const userAuth = req.user.fullName;
  if (userAuth) {
    User.findOne({ fullName: userAuth }, (err, user) => {
      if (err) console.log(err);
      res.json({ user: user.fullName });
    });
  } else {
    res.statusCode(401).json({ user: "Incorrect password or email" });
  }
})

router.route("/logout").get((req, res,next) => {
  req.logout(function(err) {
    if (err) { return next(err); }
    console.log('the user has logged out!');
    res.json({user: "logout success!"});
  });
});

passport.serializeUser((user, done) => {
  done(null, user._id);
});

passport.deserializeUser((id, done) => {
  User.findOne({ _id: new ObjectID(id) }, (err, doc) => {
    done(null, doc);
  });
});

const customFields = {
  usernameField: "email",
};

passport.use(
  new LocalStrategy(customFields, (email, password, done) => {
    User.findOne({ email }, (err, user) => {
      console.log(`User ${user.email} attempted to log in.`);
      if (err) return done(err);
      if (!user) return done(null, false);
      if (!bcrypt.compareSync(password, user.password)) {
        return done(null, false);
      }
      return done(null, user);
    });
  })
);

module.exports = router;

Are you saying if you POST to http://localhost:5000/student/login on the front-end it redirects to http://localhost:5000/admin/login

Does it do that no matter what, or only on failed sign-in?

Are you sure there isn’t an issue with the React code?

Maybe try without doing any server-side redirect (like failureRedirect) and just send and use responses on the front end to make routing decisions. I assume looking at the code you are not serving the React app using Express?

I would suggest you post a GitHub repo so people can see all the code and test it.


Move the User ${user.email} attempted to log in. console.log to after the if statements (error handling) in the route handler so the log statement doesn’t throw an error. Or use optional chaining on the logging user?.email.

yes,no matter what.

no issue,this problem arise when i change/created the admin and teacher routes.

there is no server side rendering.
***i have asked on stack over flow
and they tell me it is because of multiple passport usage i am trying to figure out that.will post the github,in a minutes.

any updates?