您的位置:首页 > 其它

koa练习

2017-11-27 23:40 134 查看

前言

2017年11月27日 参照 阮一峰老师的koa教程 自己手写了一遍所有的例子,感觉很舒服,读书千遍不如手写一遍,确实有道理。

以下,仅将阮一峰老师的koa教程 中的文字部分在此做个简单记录,一些环境准备和基础的东西,此处不做说明。

阮一峰老师的koa教程demo地址:https://github.com/ruanyf/koa-demos

我在此基础上,自建了me目录,重新编写了一遍demo,并参照教程说明,加了些许说明

我的代码:https://github.com/564239493/koa-demo1.git

一、基础用法

1.1 架设 HTTP 服务

只要三行代码,就可以用 Koa 架设一个 HTTP 服务。

// demos/01.js
const Koa = require('koa');
const app = new Koa();

app.listen(3000);


运行这个脚本。(后续不再累赘)

node demos/01.js


打开浏览器,访问 http://127.0.0.1:3000 。你会看到页面显示”Not Found”,表示没有发现任何内容。这是因为我们并没有告诉 Koa 应该显示什么内容。

1.2 Context 对象

Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。

Context.response.body属性就是发送给用户的内容。

使用app.use方法加载main函数。

ctx.request代表 HTTP Request。

1.3 HTTP Response 的类型

Koa 默认的返回类型是text/plain,

如果想返回其他类型的内容,可以先用ctx.request.accepts判断一下,客户端希望接受什么数据

然后使用ctx.response.type指定返回类型。

if (ctx.request.accepts('json')) {
ctx.response.type = 'json';
ctx.response.body = { data: 'Hello World' };
} else if (ctx.request.accepts('html')) {
ctx.response.type = 'html';
ctx.response.body = '<p>Hello World</p>';
}


1.4 网页模板

我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。

// demos/04.js
const fs = require('fs');

const main = ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./demos/template.html');
};


二、路由

2.1 原生路由

通过ctx.request.path可以获取用户请求的路径,由此实现简单的路由

// demos/05.js
const main = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World';
}
};


2.2 koa-route 模块

原生路由用起来不太方便,我们可以使用封装好的koa-route模块。

// demos/06.js
const route = require('koa-route');

const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
};

const main = ctx => {
ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/about', about));


2.3 静态资源

如果网站提供静态资源(图片、字体、样式表、脚本……),为它们一个个写路由就很麻烦,也没必要。koa-static模块封装了这部分的请求。

// demos/12.js
const path = require('path');
const serve = require('koa-static');

const main = serve(path.join(__dirname));
app.use(main);


2.4 重定向

有些场合,服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()方法可以发出一个302跳转,将用户导向另一个路由

// me/13.js
const redirect = ctx => {
ctx.response.redirect('/');
};

const main = ctx => {
ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/redirect', redirect));


三、中间件

3.1 Logger 功能

Koa 的最大特色,也是最重要的一个设计,就是中间件(middleware)。为了理解中间件,我们先看一下 Logger (打印日志)功能的实现。

最简单的写法就是在main函数里面增加一行

// demos/07.js
const main = ctx => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
ctx.response.body = 'Hello World';
};


3.2 中间件的概念

上一个例子里面的 Logger 功能,可以拆分成一个独立函数

// me/08.js

// logger中间件
const logger = (ctx, next) => {
console.log("请求" + `${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
// 执行下一个中间件
next();
// 以下方法会在返回时执行
console.log("返回" + `${Date.now()} ${ctx.request.method} ${ctx.request.url}`);

}

// 业务逻辑
const main = (ctx, next) => {
console.log("执行业务逻辑");
ctx.response.body = '中间件 - 洋葱理论';
}

app.use(logger);
app.use(main);


像上面代码中的logger函数就叫做”中间件”(middleware),因为它处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能。

app.use()用来加载中间件。

基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的main也是中间件。每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是next函数。只要调用next函数,就可以把执行权转交给下一个中间件。

3.3 中间件栈

多个中间件会形成一个栈结构(middle stack),以”先进后出”(first-in-last-out)的顺序执行。

如果中间件内部没有调用next函数,那么执行权就不会传递下去。

3.4 异步中间件

所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成 async 函数。

// demos/10.js
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();

const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
};

app.use(main);
app.listen(3000);


上面代码中,fs.readFile是一个异步操作,必须写成await fs.readFile(),然后中间件必须写成 async 函数。

3.5 中间件的合成

koa-compose模块可以将多个中间件合成为一个。

const compose = require('koa-compose');

const fun1 = (ctx, next) => {
console.log("方法1");
next();
}

const fun2 = (ctx, next) => {
console.log("方法2");
next();
}

const fun3 = (ctx, next) => {
console.log("方法3");
ctx.response.body = 'Hello World';
}

const middlewares = compose([fun2, fun1, fun3]);
app.use(middlewares);


四、错误处理

4.1 500 错误

如果代码运行过程中发生错误,我们需要把错误信息返回给用户。HTTP 协定约定这时要返回500状态码。Koa 提供了ctx.throw()方法,用来抛出错误,ctx.throw(500)就是抛出500错误。

// demos/14.js
const main = ctx => {
ctx.throw(500);
};


4.2 404错误

如果将ctx.response.status设置成404,就相当于ctx.throw(404),返回404错误。

// demos/15.js
const main = ctx => {
ctx.response.status = 404;
ctx.response.body = 'Page Not Found';
};


4.3 处理错误的中间件

为了方便处理错误,最好使用try…catch将其捕获。但是,为每个中间件都写try…catch太麻烦,我们可以让最外层的中间件,负责所有中间件的错误处理。

// demos/16.js
const handler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.response.status = err.statusCode || err.status || 500;
ctx.response.body = {
message: err.message
};
}
};

const main = ctx => {
ctx.throw(500);
};

app.use(handler);
app.use(main);


4.4 error 事件的监听

运行过程中一旦出错,Koa 会触发一个error事件。监听这个事件,也可以处理错误。

// demos/17.js
const main = ctx => {
ctx.throw(500);
};

app.on('error', (err, ctx) =>
console.error('server error', err);
);


4.5 释放 error 事件

需要注意的是,如果错误被try…catch捕获,就不会触发error事件。这时,必须调用ctx.app.emit(),手动释放error事件,才能让监听函数生效。

// demos/18.js`
const handler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.response.status = err.statusCode || err.status || 500;
ctx.response.type = 'html';
ctx.response.body = '<p>Something wrong, please contact administrator.</p>';
ctx.app.emit('error', err, ctx);
}
};

const main = ctx => {
ctx.throw(500);
};

app.on('error', function(err) {
console.log('logging error ', err.message);
console.log(err);
});


上面代码中,main函数抛出错误,被handler函数捕获。catch代码块里面使用ctx.app.emit()手动释放error事件,才能让监听函数监听到。

五、Web App 的功能

ctx.cookies用来读写 Cookie。

// demos/19.js
const main = function(ctx) {
const n = Number(ctx.cookies.get('view') || 0) + 1;
ctx.cookies.set('view', n);
ctx.response.body = n + ' views';
}


5.2 表单

Web 应用离不开处理表单。本质上,表单就是 POST 方法发送到服务器的键值对。koa-body模块可以用来从 POST 请求的数据体里面提取键值对。

// demos/20.js
const koaBody = require('koa-body');

const main = async function(ctx) {
const body = ctx.request.body;
if (!body.name) ctx.throw(400, '.name required');
ctx.body = { name: body.name };
};

app.use(koaBody());


5.3 文件上传

koa-body模块还可以用来处理文件上传。

// demos/21.js
const os = require('os');
const path = require('path');
const koaBody = require('koa-body');

const main = async function(ctx) {
const tmpdir = os.tmpdir();
const filePaths = [];
const files = ctx.request.body.files || {};

for (let key in files) {
const file = files[key];
const filePath = path.join(tmpdir, file.name);
const reader = fs.createReadStream(file.path);
const writer = fs.createWriteStream(filePath);
reader.pipe(writer);
filePaths.push(filePath);
}

ctx.body = filePaths;
};

app.use(koaBody({ multipart: true }));


结束

谢谢,作者阮一峰老师。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  koa