I am trying to break down code in my main app.js using node.js with express It was initially working when everything was together in the app.js but after I split them into various modules and I am trying to access the Login page, I get an error which says "Cannot GET/studentLogin" which is the login code below. The Login Page is and ejs file.
This is the User Login module code:
const express = require("express");
const bodyParser = require("body-parser");
// const student = require(__dirname '/models/studentModel');
const mongoose = require("mongoose");
// module.exports(student)
let studentSchema = {
studentID: String,
password: String,
};
let student = mongoose.model("Student", studentSchema);
const app = express.Router();
// app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
// Getting the Login Page
app.get("/studentLogin", function (req, res, next) {
res.render("studentLogin.ejs");
});
// Logining the Student in
app.post("/studentLogin", (req, res) => {
let loginID = req.body.student_ID;
let loginPassword = req.body.login_password;
student.findOne({ studentID: loginID }, function (err, student) {
if (err) {
console.log(err);
} else if (student.password != loginPassword) {
res.redirect("/");
} else {
res.render("StudentDashboard");
}
});
});
module.exports = app;
This is the app.js code below
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/Students");
const studentlogin = require(__dirname "/routes/studentlogin.js");
const app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("home");
});
app.use("/studentlogin", studentlogin);
app.listen(3000, () => {
console.log("Server is up and running");
});
Please what am I not doing right?
CodePudding user response:
You're mounting the router you export from /routes/studentlogin.js
under /studentlogin
(app.use('/studentlogin', studentlogin)
), and you're adding a route into that router with the suffix /studentLogin
(app.get('/studentLogin', ...
).
IOW, as it is you would need to navigate to /studentlogin/studentLogin
to see that view, or just mount the router at the root with
app.use(studentlogin);
You also don't need to configure the body parser separately in the router module, just do that on the top level instead.