forked from KangarooZero/tiny-koa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (58 loc) · 1.7 KB
/
app.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const TinyKoa = require('./src/tiny-koa.js');
const app = new TinyKoa();
const port = 8600;
const Router = require('./src/middleware/tiny-koa-router.js');
const router = new Router();
const cors = require('./src/middleware/tiny-koa-cors.js');
const bodyparser = require('./src/middleware/tiny-koa-body.js');
const server = require('./src/middleware/tiny-koa-static.js');
const koaCookies = require('./src/middleware/tiny-koa-cookie.js');
const views = require('./src/middleware/tiny-koa-views.js');
let render = views({
root: __dirname + '/views'
});
app.use(cors());
app.use(koaCookies());
app.use(bodyparser());
app.use(async function ck (ctx, next) {
console.log('set cookie', ctx.path);
ctx.cookies.set('path', decodeURIComponent(ctx.path));
await next ();
});
// curl http://localhost:8600/api/foo/123
router.all('/api/foo/:id', (ctx, next) => {
// console.log('/api/foo/:id');
ctx.body = {
param: {
id: ctx.params.id
},
route: '/api/foo/:id'
};
// return next(); // if match not to next
});
// curl http://localhost:8600/api/ccc
router.all('/api/bar', (ctx, next) => {
// console.log('/api/bar');
ctx.body = {
route: '/api/bar'
};
// return next(); // if match not to next
});
// doT测试
router.all('/page/tpl', async (ctx, next) => {
ctx.body = await render('tiny', {title: 'tiny dot template', body: 'powered by doT'});
});
let routeMiddleware = router.routes();
app.use(routeMiddleware);
app.use(async (ctx, next) => {
console.log('body test', ctx.req.body);
if (ctx.path === '/api/fetch') {
ctx.body = ctx.req.body;
} else {
return next();
}
});
app.use(server(__dirname + '/static'));
app.listen(port, () => {
console.log(`listening ${port}`);
});