问题描述
我正在使用express-handlebars
在NodeJS中加载动态内容
I am using express-handlebars
to load dynamic content in NodeJS
内部app.js
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const pp = require("./util/path.js");
const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const expressHbs = require("express-handlebars");
const app = express();
app.engine("hbs",expressHbs());
app.set("view engine", "hbs");
app.set("views", "views");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use("/admin", adminRoutes.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render("404", { pageTitle: "Page Not Found" });
});
app.listen(3001, "localhost", () => console.log("Listening on 3001 PORT"));
expressHbs()
函数没有参数时,将显示以下错误
When expressHbs()
function has no param it shows the following error
当我将选项对象传递给它时:
And when i pass an option object to it:
app.engine(
"hbs",
expressHbs({
extname: "hbs",
layoutsDir: path.join(__dirname, "views")
})
);
它显示:
我一直在寻找解决方案,但没有结果,实际上,我正在按照教程进行操作,与老师的操作相同,但是出现错误.
I've searched for a solution but i got no result , Actually i am following a tutorial and i have done the same as teacher did but i got an error.
我最近尝试过的事情是添加 defaultLayout 属性,它可以工作并加载默认值,但是当我将网址更改为另一页时,它总是加载我设置为默认值的同一页面
Lastly thing that i have tried is adding defaultLayout property and it works and load the default but when i change the url to another page it always load the same page which i set as default
这是项目文件夹及其所有内容
Here is project folder and all its contents
推荐答案
实际上express-handlebars
有点烦人,但解决了以下问题:
Actually it's a bit annoying problem with express-handlebars
but got it solved as following:
- 我必须创建一个不是
Routes
之一的独立文件,并将其名称分配给defaultLayout
- 我必须将路径设置为
views/layouts/
- 我必须为已定义的扩展名定义
extname
- I had to create a standalone file which's not one of
Routes
and assign its name todefaultLayout
- I had to set the path to
views/layouts/
- I had to to define
extname
to the extension i had defined
app.engine(
"hbs",
expressHbs({
extname: "hbs",
defaultLayout: "main-layout",
layoutsDir: "views/layouts/"
})
);
这篇关于错误:ENOENT:Express-Handlebars中没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!