首页 > 解决方案 > 如何在node / express js中访问hbs引擎视图目录中的文件夹中的文件

问题描述

希望你们都做得很好,我是 Expressjs 的新手并在其中做一个项目。实际上,我在渲染位于视图目录中名为 index.hbs 的文件夹中的文件时遇到问题,当我尝试访问时发现此错误:错误:无法在视图目录“C”中查找视图“/blogger_dasboard” :\Users\HBK1007\Desktop\ExpressjsFyPEPakTourisum\template\views"

我还附上了文件夹结构图像和我的代码

这是代码在这里输入图像描述 `

const express = require("express")
const app = express()
const path = require('path')
const port = 8000;
const hbs =require('hbs')
const bcrypt =require("bcryptjs")

// establishing db connection 
require('./db/db_connec');

// Getting the collection of DB 
const Registration=require('./models/registrationdb')
const NewsletterSubsciber=require('./models/newsletter')
const ContactUs_Client =require("./models/contactus")



// this is for DB data conersions 
app.use(express.json());
app.use(express.urlencoded({extended:false}))


//public static port
const static_path = path.join(__dirname, '../public')
const tempalte_path = path.join(__dirname, '../template/views')
const bloggerdashboard_path = path.join(__dirname, '../template/views/blogger_dashboard')
const partials_path =path.join(__dirname,'../template/particles')





app.set('view engine', 'hbs');
app.set('views', tempalte_path)

hbs.registerPartials(partials_path)
app.use(express.static(static_path))














// BloggerDashboard Routes
app.get('/blogger_dashboard', (req, res) => {
    res.render('/blogger_dasboard')
})


app.listen(port, () => {
    console.log("Listning to portss ")
})

标签: expresshandlebars.jsrenderrouter

解决方案


我镜像了你的项目,你有几个错误:

  1. static_path错误的路径,在 : , tempalte_path, bloggerdashboard_path,中一个点太多了partials_path

  1. res.render("/blogger_dasboard")这样的:res.render("blogger_dashboard"); 没有斜线,你错过了h字母。

下面的工作示例没有static_path bcryptdb(出于明显的原因)..

const express = require("express");
const app = express();
const path = require("path");
const port = 8000;
const hbs = require("hbs");
// const bcrypt = require("bcryptjs");

// establishing db connection
// require("./db/db_connec");

// Getting the collection of DB
// const Registration = require("./models/registrationdb");
// const NewsletterSubsciber = require("./models/newsletter");
// const ContactUs_Client = require("./models/contactus");

// this is for DB data conersions
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//public static port
// const static_path = path.join(__dirname, "./public");
const tempalte_path = path.join(__dirname, "./template/views");
const bloggerdashboard_path = path.join(
  __dirname,
  "./template/views/blogger_dashboard.hbs"
);
const partials_path = path.join(__dirname, "./template/particles");

app.set("view engine", "hbs");
app.set("views", tempalte_path);

hbs.registerPartials(partials_path);
// app.use(express.static(static_path));

// BloggerDashboard Routes
app.get("/blogger_dashboard", (req, res) => {
  res.render("blogger_dashboard");
});

app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});

我的项目文件夹和在此处输入图像描述文件结构:


推荐阅读