使用res.render时出现Cannot GET /错误,附代码请求排查原因
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.ejsexists in theviewsfolder 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

