koa2出來已經(jīng)很長一段時間了启盛,之前一直沒有遇上可以練手的項目,這次剛好有了機會葛家,正好折騰一下户辞。
安裝
koa2需要7.6.0及以上的node版本,目的是為了支持async await語法癞谒,不需要babel支持(7.6.0以下如果使用async await語法需要babel配置)底燎。
官方推薦使用nvm去做node的版本管理。(因之前遇到的一些坑扯俱,而且對于版本管理的需求不是很大书蚪,筆者都是直接覆蓋安裝最新版本。)
yarn add koa
(當然也可以使用npm)
簡單使用
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
// 監(jiān)聽端口3000
app.listen(3000);
console.log('打開127.0.0.1:3000查看');
中間件模式
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
通過async await 來實現(xiàn)中間件的同步模式迅栅,由最上面的async開始 一只進入下一個await
中間件模式
路由模塊
使用koa-router來實現(xiàn)路由
yarn add koa-router
獨立的index.js路由文件
const Router = require('koa-router');
const users = require('./users');
const myRouter = new Router();
myRouter.use('/users', users.routes(), users.allowedMethods());
myRouter.get('/', async (ctx) => {
ctx.body = 'Hello Worlddjlhud h!';
});
module.exports = myRouter;
app.js
const myRouter = require('./routers/index');
app
.use(myRouter.routes())
.use(myRouter.allowedMethods());
一個簡單的koa2服務器就搭建好了