1.在webstorm中新建一个项目koa2demo
将该项目初始化为node项目:(在终端输入)
npm init -y
初始化会生成一个package.json。
2.安装koa
npm install koa --save
在package.json中添加了koa的依赖。
3.HelloWorld
const Koa = require('koa');
const app = new Koa();
const main = async (ctx, next) => {
// 设置response的Content-Type
ctx.response.type = 'text/html';
// 设置response的内容
ctx.response.body = '<h1>Hello World!</h1>';
};
// 对于任何请求,该服务器程序都会调用main异步函数处理请求
app.use(main);
// 监听3000端口号
app.listen(3000);
console.log('app start at port 3000 ...');
4.一个例子
可以用以下3个middleware组成处理链,依次打印日志,记录处理时间,输出HTML:
async: 异步,await: async wait(异步等待)。
const Koa = require('koa');
const app = new Koa();
// 由async标记的函数称为异步函数,在异步函数中,可以用await调用另一个异步函数,这两个关键字在ES2017中引入。
// app.use() 注册异步(async)函数,并传入ctx和next参数。
// ctx包含request对象和response对象,next表示下一个异步函数。每个异步函数做一件事情。
// await next()调用下一个异步函数。await只能用在async函数中。
// 每个异步(async)函数都称为中间件(middleware)。这些async函数即中间件组成了一个处理链。
// app.use()中注册中间件的顺序决定了middleware的next顺序。
// 如果一个middleware没有调用await next(),那么后续注册的middleware将不再执行了。
// 打印url
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`);
await next();// 调用下一个中间件(middleware)
});
// 打印耗费时间
app.use(async (ctx, next) => {
const start = new Date().getTime();// 当前时间
await next();// 调用下一个中间件(middleware)
const ms = new Date().getTime() - start;// 耗费时间
console.log(`耗费时间:${ms}ms`);
});
// 处理请求
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello World!</h1>';
});
app.listen(3000);
console.log('app start at port 3000 ...');