Justin's Words

Express 基础

创建 package.json

1
2
3
4
5
6
7
8
9
10
11
12
{
"name": "express-basis",
"main": "service.js",
"dependencies": {
"body-parser": "^1.13.3",
"express": "^4.13.3",
"jade": "^1.11.0",
"mongoose": "^4.1.4",
"morgan": "^1.6.1",
"underscore": "^1.8.3"
}
}
  • body-parser 是为了取得 req.body.param
  • express 是框架。
  • jade 是渲染引擎。
  • mongoose 操作 MongoDB
  • morgan 输出访问信息。
  • underscore 是神器

着手 service.js

npm install 之后,开始写 server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
var path = require('path');
var jade = require('jade');
var _ = require('underscore');

##### 使用 _morgan_ 输出访问信息

app.use(morgan('dev')); // log requests to the console

##### 配置 _body-parser_

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

设置端口

1
var port = process.env.PORT || 2100;

连接数据库

1
2
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/rest'); // connect to our database

添加 middleware 通过 router.use

1
2
3
4
5
6
7
8
var router = express.Router();

// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
console.log('Something is happening.');
next();
});

测试路由

1
2
3
router.get('/', function (req, res) {
res.json({message: 'hooray! welcome to our api!'});
});

添加一个 app/models/bear.js

1
2
3
4
5
6
7
8
var mongoose     = require('mongoose');
var Schema = mongoose.Schema;

var BearSchema = new Schema({
name: String
});

module.exports = mongoose.model('Bear', BearSchema);

MongoDB 添加数据和获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var Bear = require('./app/models/bear');

router.route('/bears')
.post(function (req, res) {

var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)

bear.save(function (err) {
if (err)
res.send(err);

res.json({message: 'Bear created!'});
});

})
.get(function (req, res) {
Bear.find(function (err, bears) {
if (err)
res.send(err);

res.json(bears);
});
});

添加数据库搜索、更新和删除功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
router.route('/bears/:bear_id')

// get the bear with that id
.get(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})

// update the bear with this id
.put(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {

if (err)
res.send(err);

bear.name = req.body.name;
bear.save(function (err) {
if (err)
res.send(err);

res.json({message: 'Bear updated!'});
});

});
})
// delete the bear with this id
.delete(function (req, res) {
Bear.remove({
_id: req.params.bear_id
}, function (err, bear) {
if (err)
res.send(err);

res.json({message: 'Successfully deleted'});
});
});

注册路由

意味着上述 router 操作都是在 /api 下完成的

1
app.use('/api', router);

设置模板路径、模板渲染引擎和渲染配置

1
2
3
4
app.set('views', path.join(__dirname + '/views'));
app.set('view engine', 'jade');
// 默认为 development,编译代码为 pretty
app.locals.pretty = app.get('env') != 'production';

设置静态文件路径

1
app.use('/static', express.static('public'));

设置页面数据和渲染文件

1
2
3
4
5
6
7
app.get('/', function (req, res) {
var data = {
title: 'Express',
message: 'Hello earth!'
};
res.render('index', data);
});

不适用引擎渲染时则使用 res.sendFile

1
res.sendFile(path.join(__dirname + '/view/index'));

监听端口

1
app.listen(port);

Jade 模板

views/index.jade

1
2
3
4
5
6
7
8
9
10
11
12
doctype html
html(lang='en-US')
head
meta(charset='utf-8')
link(rel='stylesheet', href='static/css/bootstrap.min.css')
title #{title}
body
.container
header.jumbotron
h1 #{message}

include common-js

common-js.jade

1
2
script(type='text/javascript', src='static/js/jquery.js')
script(type='text/javascript', src='static/js/bootstrap.min.js')

延伸阅读:Build a RESTful API Using Node and Express 4