express-handlebars报错:无法找到指定目录或文件
Hey there, let's get this handlebars issue sorted out! That ENOENT error is telling you that Express can't find the default layout file it expects: main.handlebars in the views/layouts directory. Here's why it's happening and how to fix it:
Why this happens
By default, express-handlebars looks for a main layout file at views/layouts/main.handlebars to wrap your other templates. If this file or the required directory structure doesn't exist, you'll get that missing file error.
Solution 1: Create the default layout file
- First, make sure your project has this directory structure (match your project root path):
test handlebars/ ├─ views/ │ └─ layouts/ │ └─ main.handlebars └─ server.js - Inside
main.handlebars, add the basic layout structure with the{{{body}}}placeholder—this is where your page content will be injected:<!DOCTYPE html> <html> <head> <title>Your App Title</title> </head> <body> {{{body}}} </body> </html>
Solution 2: Disable or customize the default layout
If you don't want to use a default layout, you can adjust the express-handlebars configuration in your server.js file:
const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); // Option 1: Disable default layout entirely app.engine('handlebars', exphbs({ defaultLayout: false })); // Option 2: Use a custom layout file (replace 'my-layout' with your file name) // app.engine('handlebars', exphbs({ defaultLayout: 'my-layout' })); app.set('view engine', 'handlebars'); // Rest of your server code...
Just double-check that your views folder is in the correct root directory of your project, and you should be good to go!
内容的提问来源于stack exchange,提问作者maxilaxen

