koa2 simple understanding

koa why are you called the next generation

1. Installation

$ nvm install 7
$ npm i koa
$ node my-koa-app.js

2. Introduction

koa2 developed based on ES7, compared with koa 1, koa2 completely uses Promise and cooperates with async to achieve asynchronous.

app.use(async (ctx, next) => {
    await next();
    var data = await doReadFile();
    ctx.response.type = 'text/plain';
    ctx.response.body = data;
});

3. Create koa2 project

  • First create a project directory, then create app.js
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();

// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
   //ctx.response.type = "application/json;charset=UTF-8";也可以返回json数据
   //ctx.response.body = {'name':'jack','age':12,'sex':'man'}
});

// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324941519&siteId=291194637