You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express拆分Node.js代码后访问/studentLogin报Cannot GET错误求助

问题描述

我正在使用Node.js结合Express框架拆分主app.js中的代码,原本所有代码集中在app.js时可正常运行,但拆分模块后,尝试访问作为EJS文件的学生登录页面时,出现「Cannot GET /studentLogin」错误。

用户登录模块代码(routes/studentlogin.js)

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;

app.js代码

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");
});
问题分析与解决

出现「Cannot GET /studentLogin」错误的核心原因是路由挂载路径和定义路径不匹配:

  • 在app.js中,你把学生登录路由模块挂载到了/studentlogin路径下:app.use("/studentlogin", studentlogin);
  • 但在路由模块里,你定义的登录页面路径是/studentLogin,这意味着实际可访问的完整路径应该是/studentlogin/studentLogin,而不是你尝试访问的/studentLogin。

解决方法(二选一即可)

  1. 修改路由模块中的路径定义,把/studentLogin改成/,这样挂载后访问/studentlogin就能直接打开登录页面:
// 路由模块中修改为
app.get("/", function (req, res, next) {
  res.render("studentLogin.ejs");
});

app.post("/", (req, res) => {
  // 原post逻辑不变
});
  1. 修改app.js中的挂载路径,将挂载路径改为/(不推荐,易和其他路由冲突),或者保持挂载路径与路由定义的一致性,比如把路由模块里的/studentLogin改为/,挂载路径仍用/studentlogin,这样访问逻辑更清晰。

另外补充几个优化点:

  • 路由模块里不需要重复配置bodyParser,app.js已经全局配置过,可删除路由模块中的app.use(bodyParser.urlencoded({ extended: true }));
  • 数据库模型定义建议单独抽离到models文件夹,避免和路由代码耦合
  • res.render("StudentDashboard");的模板文件名建议统一小写,和studentLogin.ejs保持一致,防止因系统大小写敏感导致模板找不到

内容的提问来源于stack exchange,提问作者RaqDeku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:39:25