koa2的安装

koa2的初步使用

koa2的安装

1
npm install koa --save

项目要使用的package(package.json)

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
{
"name": "ownkoa",
"version": "1.0.0",
"description": "koa2",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "supervisor start.js"
},
"keywords": [
"koa2",
"test"
],
"author": "scrd",
"license": "ISC",
"dependencies": {
"babel-core": "^6.21.0",
"babel-polyfill": "^6.20.0",
"babel-preset-es2015-node6": "^0.4.0",
"babel-preset-stage-3": "^6.17.0",
"koa": "^2.0.0-alpha.7",
"koa-bodyparser": "^3.2.0",
"koa-logger": "^1.3.0",
"koa-router": "^7.1.0",
"koa-views": "^5.2.0",
"nunjucks": "^3.0.0"
},
"devDependencies": {}
}

使用babel来翻译async/await(start.js)

1
2
3
4
5
6
7
var register = require('babel-core/register');
register({
presets: ['stage-3']
});
require('./app.js');

如果安装node 7.6及以上版本,你就放心用吧~~~

使用模板nunjucks,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
const koa = require('koa');
const nunjucks = require('nunjucks');
const router = require('koa-router')();
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const views = require('koa-views');
const path = require('path');
const app = new koa();
/* 配置nunjucks模板文件所在的路径,否则模板继承时无法使用相对路径. */
nunjucks.configure(path.join(__dirname + '/views'), { autoescape: true });
app.use(views(path.join(__dirname + '/views'), {
map: {
html: 'nunjucks'
}
}));
app.use(logger());
app.use(bodyparser());
router.get('/', async (ctx, next) => {
await ctx.render('index.html', {
username: '的撒范德萨范德萨'
});
});
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');

nunjucks文档:nunjucks文档

觉得不错的一个使用教程:觉得不错的一个使用教程

koa-generator使用:

1
2
3
4
npm install -g koa-generator
// koa2
koa2 xxxx