在此第2部分中,我们将在合并车把的同时定义路线。
安装车把
-
用命令安装express-handlebars
npm install express-handlebars
-
需要 index.js
中的express-handlebars
... const app = express() const handlebars = require('express-handlebars') ...
-
在Express
中设置模板引擎- 使用 .hbs 文件扩展而不是 .handlebars
- 默认布局名称为 app
- 添加用于显示完整路线和ENV变量的助手功能
... app.engine( '.hbs', handlebars.engine({ // use hbs instead of handlebars extension extname: '.hbs', // default layout name defaultLayout: 'app', // simple template functions helpers: { // return the full route path route(path) { return process.env.APP_URL + ':' + process.env.APP_PORT + path }, // returns the env variable value config(name) { return process.env[name] }, }, }) ) app.set('view engine', '.hbs') // use views folder app.set('views', __dirname + '/views') // static folder app.use(express.static('public')) ...
创建视图
-
将
APP_URL
添加到 .env 文件
APP_URL=http://localhost
-
创建主布局 app.hbs 视图/布局
-
route
辅助功能在这里用于获取Favicon的完整路径 -
config
助手功能用于获取ENV变量APP_NAME
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="icon" type="image/png" href="{{route '/favicon.png' }}" /> <title>{{config 'APP_NAME' }}</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-100"> {{{ body }}} </body> </html>
-
-
在 public 文件夹中添加favicon,名为
favicon.png
-
创建主页内容 index.hbs 视图文件夹
<div class="min-h-screen flex flex-col"> <div class="min-h-screen flex justify-center flex-wrap content-center"> <div class="bg-gray-100 rounded-md w-10/12 md:w-1/2 lg:w-4/12 flex flex-col shadow"> <div class="w-full p-8 flex flex-wrap content-center bg-white"> <div class="flex w-full justify-center"> <a href="{{route '/' }}">Homepage</a> </div> </div> </div> </div> </div>
路由器
-
delete 以下代码,因为我们将在 index.js
中添加控制器和路由器文件... const { ServerError } = require('./exceptions/ServerError') ... app.get('/', async (req, res, next) => { // res.send('Hello World!') try { // res.send('hello') throw new ServerError() } catch (error) { return next(error) } })
-
创建 index.js 路由文件夹
const router = require('express').Router() // home page route router.get('/', async (req, res) => { // this will render the index.hbs with the default app.hbs layout return res.render('index') // to switch the layout file called main.hbs (make sure it is created in views/layouts) /** return res.render('index', { layout: 'main', }) */ }) module.exports = router
-
现在确保应用程序知道使用路线/index.js
... app.use('/', routes) app.use(errorHandler.logger) ...