一、前期准备
1.下载node和MongoDB
2. 掌握前端的基础知识,比如html,css,jquery,js,bootstrap
3.了解Express,看看中文文档
4.了解MongoDB,可以先去菜鸟看看
二、创建项目骨架
1.创建项目
1)MyApp
创建一个叫做MyApp的项目,下载它的依赖项目,并启动服务,在浏览器输入localhost:3000
E:\node\express MyAPP -e
E:\node\cd MyApp && npm install
E:\node\MyApp node ./bin/www
2)bower
在全局安装bower,官网是这样介绍
Web sites are made of lots of things — frameworks, libraries, assets, and utilities. Bower manages all these things for you.
bower和npm 类似,可理解为包管理工具
E:\node\MyApp npm install bower -g
用bower下载jquery和bootstrap,下载完成之后我们可以发现,项目中多了一个“bower_components”的文件夹,jquery和bootstrap已经在里面了
E:\node\MyApp bower install jquery bootstrap
三、创建路由和视图
1.创建路由
我们搭建的电影网站,需要有首页、详情页、后台录入页、列表页。打开routes下的index.js添加相应的路由
router.get('/', function(req, res, next) {
res.render('index', { title: '首页' });
});
router.get('/movie/:id', function(req, res, next) {
res.render('detail', { title: '详情页' });
});
router.get('/admin/movie', function(req, res, next) {
res.render('admin', { title: '后台录入页' });
});
router.get('/admin/list', function(req, res, next) {
res.render('list', { title: '列表页' });
})
2.创建视图
在views文件夹下面分别创建以下几个页面:detail.ejs、admin.ejs、list.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
3.测试流程
1)开启服务
如果router这边修改了,必须要重新启动服务才可以刷新;视图修改了直接在浏览器刷新就可以看到效果
E:\node\MyApp node ./bin/www
2)测试流程
地址栏输入路由,测试页面是否能正常显示
localhost:3000
localhost:3000/movie/:1
四、伪造数据
1.修改视图
1)layout
在views页面创建pages文件夹,把页面都放到pages下面;创建layout页面,里面创建header.ejs和footer.ejs。因为很多页面会有相同的部分,比如头部和尾部,我们可以把这些放在一个文件夹。在页面通过 include 引用进去就可以了
header.ejs
<!DOCTYPE html>
<