当我点击http://localhost:4444/admin/posts/create
时,我的渲染路径是正确的,但显示出一些错误,例如
Error: Failed to lookup view "/admin/posts/create" in views directory "D:\node practise\CMS\views"
app.js 文件就像
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cms', { useNewUrlParser: true })
.then(db => {
console.log('MONGO CONNECTED!');
})
.catch(error => {
console.log('MONGO NOT CONNECTED!');
})
//making app to use static file
app.use(express.static(path.join(__dirname, 'public')));
//define template engine
app.set('view engine', 'handlebars');
//set default engine
app.engine('handlebars', exphbs({defaultLayout: 'home'}));
//load routes
const home = require("./routes/home/index");
const admin = require("./routes/admin/index");
const posts = require("./routes/admin/posts");
//use routes
app.use(home);
app.use("/admin", admin);
app.use("/admin/posts", posts);
//setting up server
app.listen(4444, () => {
console.log('Listening....');
});
我有posts.js可以像这样处理这条路线
const express = require("express");
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
})
router.get('/', (req, res) => {
res.send('It works!');
})
router.get('/create', (req, res) => {
res.render('/admin/posts/create');
})
module.exports = router;
可能是错误原因?当我尝试发送响应时,它可以工作,但是当我尝试呈现视图时,它显示错误。
答案 0 :(得分:2)
您可以尝试res.render('admin/posts/create');
吗?
如果正确设置了视图文件夹:app.set('views', './views')
,则应该能够解析res.render('myview')
文件夹下的简单视图名称,例如./views