一、创建项目并进入
$ mkdir project
$ cd project
二、快速生成 package.json 文件
$ npm init -y
三、安装 Koa
$ npm i koa
四、创建 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(); // 设置response的Content-Type: ctx.response.type = 'text/html'; // 设置response的内容: ctx.response.body = '<h1>Hello, koa2!</h1>'; }); // 在端口3000监听: app.listen(3000); console.log('app started at port 3000...');
其中,参数 ctx
是由 koa 传入的封装了 request 和 response 的变量,我们可以通过它访问 request 和 response,next
是 koa 传入的将要处理的下一个异步函数。
上面的异步函数中,先用 await next();
处理下一个异步函数,然后设置 response 的 Content-Type 和内容。
五、启动程序
$ node app.js