60分钟学会使用Node.js+Express+Ejs+mongoDB
本文出自从零到壹全栈部落
第1部分 – 15分钟安装
- 第1步 - 环境安装
请直接移步Node.js官网,如下图所示,直接点击最新版下载并进行安装。
Node.js安装完毕后,打开终端,在终端分别输入如下命令,检测是否安装成功。
Last login: Tue Jun 27 09:19:38 on console
liyuechun:~ yuechunli$ node -v
v8.1.3
liyuechun:~ yuechunli$ npm -v
5.0.3
liyuechun:~ yuechunli$
如果能够正确显示node和npm的版本,说明Node.js安装成功。
- 第2步 - 安装Express
Last login: Mon Jul 10 11:14:16 on ttys001
liyuechun:~ yuechunli$ npm install -g express
+ express@4.15.3
added 42 packages in 7.337s
liyuechun:~ yuechunli$
- 第3步 - 创建一个Express项目
我们准备使用Express
和Ejs
,这不是用来做CSS预处理的。我们会手写一些CSS。我们要用Ejs或者其它的模板引擎来处理Node和Express的数据。如果你会HTML的话,Ejs并不难。只要记住你需要集中精神,否则很容易出错。
liyuechun:Desktop yuechunli$ pwd
/Users/liyuechun/Desktop
liyuechun:Desktop yuechunli$ mkdir 60MINUTES
liyuechun:Desktop yuechunli$ cd 60MINUTES/
bogon:60MINUTES yuechunli$ express -e nodetest1
warning: option `--ejs' has been renamed to `--view=ejs'
create : nodetest1
create : nodetest1/package.json
create : nodetest1/app.js
create : nodetest1/public
create : nodetest1/views
create : nodetest1/views/index.ejs
create : nodetest1/views/error.ejs
create : nodetest1/routes
create : nodetest1/routes/index.js
create : nodetest1/routes/users.js
create : nodetest1/bin
create : nodetest1/bin/www
create : nodetest1/public/javascripts
create : nodetest1/public/stylesheets
create : nodetest1/public/stylesheets/style.css
install dependencies:
$ cd nodetest1 && npm install
run the app:
$ DEBUG=nodetest1:* npm start
create : nodetest1/public/images
bogon:60MINUTES yuechunli$
VSCode打开,项目结构如下:
- 第4步 - 编辑依赖项
好了,我们现在有一些基本项目结构,但是还没完。你会注意到express的安装过程在你的nodetest1目录里创建了一个叫package.json
的文件,用文本编辑器打开这个文件,它应该是长这样的:
{
"name": "nodetest1",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"ejs": "~2.5.6",
"express": "~4.15.2",
"morgan": "~1.8.1",
"serve-favicon": "~2.4.2"
}
}
这是一个标准的JSON格式文件,表明了我们应用的依赖。我们需要添加一点东西。比如对mongodb和Monk的调用。把dependencies部分改成这样:
{
"name": "nodetest1",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"ejs": "~2.5.6",
"express": "~4.15.2",
"morgan": "~1.8.1",
"serve-favicon": "~2.4.2",
"mongodb": "*",
"monk": "*"
}
}
- 第5步 – 安装依赖
现在我们定义好了项目的依赖项。*号会告诉NPM“安装最新版本”。回到命令行窗口,进入nodetest1目录,输入:
bogon:nodetest1 yuechunli$ ls
app.js package.json routes
bin public views
bogon:nodetest1 yuechunli$ npm install
npm notice created a lockfile as package-lock.json. You should commit this file.
added 80 packages in 4.563s
bogon:nodetest1 yuechunli$ npm start
> nodetest1@0.0.0 start /Users/liyuechun/Desktop/60MINUTES/nodetest1
> node ./bin/www
Express server listening on port 3000...
GET / 200 13.288 ms - 207
GET /stylesheets/style.css 200 3.295 ms - 111
GET /favicon.ico 404 1.757 ms - 1136
浏览器输入http://127.0.0.1:3000
,效果图如下:
第2部分 – 好了,我们来写“Hello, World!”吧
- 查阅
app.js
源码
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
console.log("Express server listening on port 3000...");
module.exports = app;
app.js
中添加代码
现在,我们写点有用的。我们不会直接在我们的index页面里写“Hello World!”,我们借这个机会学习一下如何使用route路由,同时学习一下Ejs引擎是如何工作的。在上面的app.js文件中添加如下
两行代码:
- 创建
helloworld.js
文件
内容如下:
var express = require('express');
var router = express.Router();
/* GET HelloWorld page. */
router.get('/', function(req, res, next) {
res.render('helloworld', { title: 'HelloWorld' });
});
module.exports = router;
- 创建
helloworld.ejs
文件
内容如下:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
</body>
</html>
-
运行程序
npm start
启动服务器,然后在浏览器打开http://localhost:3000/helloworld
,应该能看到这个漂亮的界面了: - ejs⚠️去除
如上图所示,在VSCode中使用ejs
代码会出现语法不识别的问题,启动VSCode,通过快捷键⌘+P
快速打开窗口,将如下代码拷贝粘贴到里面,回车安装插件,然后重启即可。
ext install ejs-language-support
扫码申请加入全栈部落 | |
---|---|
 |
第3部分 – 创建数据库并读取数据
- 第1步 - 更新HomeBrew
Last login: Wed Jul 12 09:27:06 on ttys000
liyuechun:~ yuechunli$ brew update
Updated 1 tap (homebrew/core).
==> Updated Formulae
radare2
- 第2步 – 安装Mongodb
liyuechun:~ yuechunli$ brew install mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.4.6.sierra.bottle
Already downloaded: /Users/liyuechun/Library/Caches/Homebrew/mongodb-3.4.6.sierra.bottle.tar.gz
==> Pouring mongodb-3.4.6.sierra.bottle.tar.gz
==> Using the sandbox
==> Caveats
To have launchd start mongodb now and restart at login:
brew services start mongodb
Or, if you don't want/need a background service you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary