我需要一个客户来给页面。我做了一个简单的node.js服务器。
项目结构
| web-site (folder)
| package.json (files)
| package-lock.json (files)
| node_modules (folder)
...
| src (folder)
| index.js (files)
| routers (folder)
| routesr.js (files)
| views (folder)
| index.hbs (files)
...
Index.js文件内容。
import express from 'express'
import routers from './routers/routers';
const port = process.env.PORT || 8081;
const router = express();
router.set('views', __dirname + '/views/');
router.set('view engine', 'hbs');
router.use(express.static('./../public'));
router.use(routers);
router.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
export default router;
routers.js文件内容。
import express from 'express'
const router = express();
router.get('/', (req, res) => {
const peopleList = getRandomList();
res.render('index', { people: peopleList });
});
export default router;
const getRandomList = () => {
const list = ['ada', 'turing', 'lovelace', 'neumann', 'gracehopper'];
const limit = Math.floor(Math.random() * (list.length - 1 - 0) + 0);
return list.slice(limit);
};
index.hbs文件内容。
<!DOCTYPE html>
<html>
<body>
<ul>
{{#each people}}
<li>{{this}}</li>
{{/each}}
</ul>
</body>
</html>
在浏览器中打开路线http://localhost:8081
时出现错误
错误:无法在视图目录“ C:\ Users \ user \ Documents \ website \ views”中查找视图“索引”
为什么我的服务器看不到index.hbs文件?
答案 0 :(得分:1)
尝试改变
router.set('views', __dirname + '/views/');
到
router.set('views', path.join(__dirname, 'views/'));