NodeJS Express路由器未路由到正确路由

hlswsv35  于 2023-01-25  发布在  Node.js
关注(0)|答案(1)|浏览(186)

我有3个单独的文件用于学生、教师和管理员路由,并在server.js文件中使用use方法将其用作通用中间件。当我使用react在前端使用axios .post("http://localhost:5000/student/login", user)路由时,它一直转向管理员路由。我不明白?我定义的中间件是否错误或什么?服务器控制台显示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;
4xrmg8kj

4xrmg8kj1#

确保您正在向端点发送正确的数据。根据给出的错误,您没有发送请求中的“电子邮件”属性。

相关问题