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

使用Express.js构建MVC项目时首页显示Cannot GET /错误

Node.js MVC项目首页显示Cannot GET /问题排查

我是Node.js新手,跟着讲解视频和官方文档用MVC结构开发网站,服务器能正常启动,但访问首页时浏览器提示Cannot GET /。

项目代码如下:

index.js

'use strict';
/* eslint-env node, es6 */

const express = require('express');
const app = express();
app.set('view engine', 'ejs');

const PORT = process.env.PORT || 4242;

app.use('/', require('./routes/home_route'));

app.listen(PORT, () => {
    console.log(`serveur démaré: localhost:${PORT}`);
});

home_controller.js

'use strict';

const homeView = (req, res) => {
    res.render("home_view", {
    } );
}
module.exports =  { homeView };

home_route.js

'use strict';

const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
module.exports = router;

home_view.ejs仅包含HTML代码。


问题原因

你的路由配置里只定义了/home路径的GET请求处理,但访问根路径/时没有对应的路由匹配,所以Express返回404错误。

解决方案

有两种修改方式,任选其一即可:

  1. 给根路径添加路由处理
    在home_route.js中新增一行根路径的路由:
router.get('/', homeView); // 新增这行
router.get('/home', homeView);
  1. 将现有路由改为根路径
    把home_route.js中的/home路由改成根路径:
router.get('/', homeView); // 替换原有的router.get('/home', homeView);

另外需要确认home_view.ejs文件放在项目的views目录下(Express默认会从views目录加载模板),如果模板文件位置不在默认目录,需要通过app.set('views', './指定模板目录路径')来配置路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:37:00