-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress-demo.js
49 lines (41 loc) · 1.11 KB
/
express-demo.js
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
40
41
42
43
44
45
46
47
48
49
const http = require('http');
const express = require('express');
const app = new express();
// app 实例级配置, 最终设置到 app._router 中去
app.use(function (req, res, next) {
console.log(`app set middleware`);
next()
});
app.get('/', function (req, res, next) {
res.end(`hello express`);
});
app.post('/', function (req, res, next) {
res.json({
path: '/',
method: 'post'
});
});
// 单个 router 设置
const routerA = express.Router();
routerA.param('id', function (req, res, next, id) {
console.log(`app.param id: ${id}`);
next();
});
routerA.get('/user/:id', function (req, res, next) {
res.end(`id is ${req.params.id}`);
});
app.use('/a', routerA);
// 单个 router 设置
const routerB = express.Router();
routerB.get('/', function (req, res, next) {
res.end(`this is router B root path`);
});
app.use('/b', routerB);
// 全局异常处理
app.use(function (err, req, res, next) {
console.log(`${err}`);
res.statusCode = 500;
res.end();
});
const server = http.createServer(app);
server.listen(3000, () => console.log(`express has listen`));