本地图书馆项目
郭旭升 Lv6

目标

  • 为一家小型本地图书馆提供线上图书编目而建,
  • 用户可以能够浏览馆藏书目,还能管理自己的帐号。

项目地址

资源

https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website
通过构建项目的过程学习express框架核心知识以及项目架构,也学习了web开发到部署的流程。

技术点总结

  • 使用 Express 应用生成器创建一个应用骨架。
  • 启动和停止 Node web 服务器。
  • 使用数据库存放应用数据。
  • 创建路由来处理不同信息的请求,创建模板(”视图”)来渲染 HTML 数据以在浏览器中显示。
  • 使用表单。
  • 部署应用到生产环境。

创建框架

创建一个可添加路由、模板/视图、和数据库调用的“骨架”站点。

nodemon 是最简便的自动化工具之一,添加了这个依赖就可以不重启的情况下修改程序并展示效果。
在Package.json文件中添加脚本

1
2
3
4
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},

npm run devstart 这样就可以运行中使用它了。
现在,如果编辑项目中的任何文件,服务器将自动重启(或者可以随时使用 rs 命令来重启)。查看更新后的页面需要点击浏览器的“刷新”按钮。

package.json 中的脚本解析

“scripts” 部分,定义了一个 “start” 脚本,当运行 npm start 时会调用它来启动服务器。在脚本定义中可以看到 start 实际上运行了 “node ./bin/www”。还有一个 “devstart” 脚本,可以通过运行 npm run devstart 来运行 “nodemon ./bin/www”。

www文件

文件 /bin/www 是应用入口!它做的第一件事是 require() “真实”的应用入口(即项目根目录中的 app.js ),app.js 会设置并返回 express()应用对象。
文件的其余部分先为 app 设置端口(环境变量中的预定义值或默认值 3000),再创建一个 HTTP 服务器,然后开始监听请求,报告服务器错误和连接信息。

路由

路由是一段 Express 代码,它将 HTTP 动词(GET、POST、PUT、DELETE 等)、URL 路径/模式和处理函数三者关联起来。

问题

1. 不用callback了,而是换成了promise的方法

原因:
Promises allow you to chain multiple asynchronous operations together and handle errors in a more elegant way than callbacks.

问题:
throw new MongooseError(‘Query.prototype.exec() no longer accepts a callback’);
^
MongooseError: Query.prototype.exec() no longer accepts a callback

解释:
In previous versions of Mongoose, you could pass a callback function to the exec() method to handle the results of the query. However, in more recent versions of Mongoose, the exec() method returns a Promise instead.

更改:

1
2
3
4
5
6
7
8
9
10
exports.author_list = (req, res, next) => {
Author.find({})
.sort([['family_name', 'ascending']])
.then(authors => {
res.render('author_list', { title: 'Author List', author_list: authors });
})
.catch(err => {
next(err);
});
};
 Comments