Node.js Web应用无法提供页面,访问时返回Cannot GET /page
Node.js Web应用“Cannot GET /page”错误排查与修复
核心问题
你遇到的Cannot GET /page错误,本质是目标路径未配置对应的路由处理逻辑,同时代码中存在路由定义位置错误、目录结构描述模糊等问题,导致服务器无法识别并响应/page请求。
具体错误点及修复方案
1. 路由定义位置错误
你在app.listen()的回调函数中再次定义了根路由app.get('/'),但服务器启动后(app.listen()执行后)注册的路由不会生效,属于无效代码,且和之前的根路由定义重复。
修复:删除app.listen()回调内的路由代码,确保所有路由都在服务器启动前注册。
2. 缺少/page对应的路由处理
当前代码仅配置了根路径/的路由,没有为/page添加任何处理逻辑,这是直接导致Cannot GET /page的原因。
修复:根据你的views/pages目录结构,添加对应路由:
// 假设page对应的视图文件是views/pages/page.html app.get('/page', (req, res) => { res.render('pages/page'); });
3. 目录结构描述模糊
你的views/pages下写的login, and messages.不符合实际文件格式,应该是具体的HTML文件(如login.html、messages.html),否则渲染时会找不到文件。
确认:确保views/pages目录下存在对应的page.html文件,或者调整路由中的渲染路径匹配实际文件名。
4. 模板引擎渲染路径验证
你配置了用ejs渲染HTML文件,res.render()的路径是基于views目录的相对路径,所以如果页面在views/pages下,必须写成res.render('pages/xxx'),而不是直接写文件名。
修复后的完整server.js示例
const express = require('express'); const path = require('path'); const app = express(); const PORT = 3000; // 确保PORT已定义 // Serve static files from 'public' directory app.use(express.static(path.join(__dirname, 'public'))); // Custom middleware to handle .html extension removal app.use((req, res, next) => { if (req.path.endsWith('.html')) { const newPath = req.path.slice(0, -5); // Remove the .html extension return res.redirect(newPath); } next(); }); // Serve HTML views from 'views' directory app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.engine('html', require('ejs').renderFile); // Root route app.get('/', (req, res) => { res.render('index'); // 确保views目录下存在index.html }); // 添加/page路由 app.get('/page', (req, res) => { res.render('pages/page'); // 确保views/pages下存在page.html }); // Models const User = require('./models/User'); // 引入并使用路由文件(如果之前没做的话) const authRoutes = require('./routes/authRoutes'); const productRoutes = require('./routes/productRoutes'); app.use('/auth', authRoutes); app.use('/products', productRoutes); // Start Server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
额外检查点
- 确认所有依赖已安装:执行
npm install express ejs确保依赖齐全。 - 检查文件路径是否大小写匹配:Node.js在类Unix系统下区分大小写,确保文件名和路由中的路径一致。
- 测试其他路由:如果
/login等路径也有问题,需要为它们添加对应的路由处理。
内容的提问来源于stack exchange,提问作者Savage
相关产品推荐
相关产品推荐

