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

使用res.render时出现Cannot GET /错误,附代码请求排查原因

Fixing the "Cannot GET /" Error in Your Express App

Hey there, let's break down why you're hitting that frustrating Cannot GET / error and fix it right away!

The Root Cause

Looking at your code, the issue lies in how you're calling res.render() for your root route:

res.render( "/views/home.ejs");

When you set app.set('view engine', 'ejs'), Express automatically looks for template files in the project's views directory by default. You don't need to include the full path or the .ejs extension here—Express handles those details for you. Using the absolute path /views/home.ejs makes Express look for a views folder at the root of your filesystem (not your project folder), which is why it can't locate the template and throws the error.

Fixed Code

Here's the corrected version of your server code:

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

// Corrected render call
app.get("/" , function(req,res){
  res.render('home'); // Just the filename without path or extension
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

Quick Checks to Ensure It Works

  • Confirm your project structure matches this:
    your-project/
    ├── views/
    │   └── home.ejs
    ├── public/
    └── app.js (your main server file)
    
  • Double-check that home.ejs exists in the views folder and has valid content.
  • Restart your Express server after making the change—servers often don't pick up edits automatically.

That should resolve the Cannot GET / error and render your home page properly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:42:28