使用Express.js搭配EJS时出现500内部服务器错误
Hey there! Let’s work through this 500 error you’re hitting when setting up EJS with Express. From the code snippet you shared, here are the most common fixes that usually resolve this issue:
Make sure EJS is installed
It’s easy to forget this step! Run this command in your project directory to install EJS as a dependency:npm install ejs --saveIf EJS isn’t installed, Express won’t be able to locate the view engine, which triggers a 500 error.
Simplify your view engine setup (skip
consolidateif you don’t need it)
EJS is natively supported by Express, so you don’t need theconsolidatemodule unless you’re using multiple template engines. Replace your current engine setup with these lines:// Set the directory where your EJS files live app.set('views', path.join(__dirname, 'views')); // Tell Express to use EJS as the view engine app.set('view engine', 'ejs');Double-check that your
viewsfolder exists in the root of your project and contains your EJS files (likeindex.ejs).If you do need
consolidate, configure it correctly
If you’re usingconsolidatefor other engines, make sure you register EJS properly:app.engine('ejs', engines.ejs); app.set('view engine', 'ejs');Fix any syntax errors in your code
The snippet you shared cuts off atvar main = requi...—that looks like a typo (requireis missing the finalr). Syntax errors like this will crash your server and throw a 500 error. Go through yourapp.jsto ensure allrequirestatements are complete and there are no missing brackets or semicolons.Enable detailed error logging to pinpoint the issue
Add an error-handling middleware to your Express app to see exactly what’s causing the 500 error. This will show you specific details like missing files or EJS syntax mistakes:app.use(function(err, req, res, next) { // Set error status code res.status(err.status || 500); // Render an error page (create error.ejs in your views folder if needed) res.render('error', { message: err.message, error: err // Show full error details in development; use {} in production }); });Check your route rendering code
Make sure your routes are callingres.render()with the correct filename (without the.ejsextension). For example:// Correct res.render('index'); // Incorrect (will cause a file not found error) res.render('index.html');
Try these steps one by one—detailed error logs are especially helpful here because they’ll tell you exactly what’s broken. Let me know if you still run into issues after checking these!
内容的提问来源于stack exchange,提问作者Nguyen Hoang Vu

