
上QQ阅读APP看书,第一时间看更新
4.9 留言板项目开发
本节将和大家一起使用所学的知识开发一个Web留言板。
项目的功能如下:
· 首页展示留言列表和发布按钮。
· 发布页面展示留言表单,单击发布后保存留言。
本节的留言数据存储在内存中,进程结束留言板数据会丢失。数据库相关的知识在后面的章节中介绍。
4.9.1 开始编码
初始化项目并安装相关依赖:

下面列出本项目的完整代码。
index.js

在index.js的同级新建templates/index.ejs来存放首页模板。
templates/index.ejs

该模板文件对留言内容进行了判空处理,没有留言内容就显示“当前没有留言。”,有留言内容就显示留言列表。
在index.js的同级新建templates/publish.ejs来存放发布页模板。

4.9.2 运行项目
node inde.js
浏览器访问http://localhost:8080,首页效果如图4-1所示。

图4-1
单击【发表留言】,发布页效果如图4-2所示。

图4-2
输入姓名和内容后,单击【发表】自动重定向到首页,首页效果如图4-3所示。

图4-3
恭喜!你的第一个Express应用已经运行成功了!如果遇到问题可以咨询作者的公众号。
回顾一下一个Express应用的开发流程:
(1)初始化项目。
(2)安装依赖。
(3)编写路由文件,并导入中间件。
(4)编写模板文件。
(5)运行项目并测试。