Initialization package.json
npm init
AnSo koa
npm install koa
Creating app.js
// 导入的是一个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, world!</h1>';
});
// 在端口3005监听:
app.listen(3005);
Parameters ctx
are passed by the koa encapsulates request
and response
variables can be accessed through it request
and response
. next
Koa is passed in the next asynchronous function to be processed.
The async
function is called asynchronous marker function in an asynchronous function, you can await
call another asynchronous function.
start up
npm start
You can start your tour of koa