{"name":"hello-koa2","version":"1.0.0","description":"Hello Koa 2 example with async","main":"app.js","scripts":{"start":"node app.js"},"keywords":["koa","async"],"author":"","license":"Apache-2.0","repository":{},"dependencies":{"glob":"^7.1.3","koa":"^2.0.0","koa-bodyparser":"3.2.0","koa-compose":"^4.1.0","koa-router":"7.0.0"}}
3 ,在控制台中输入 npm install
4,在app.js 中;
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:const Koa =require('koa');// 创建一个Koa对象表示web app本身:const app =newKoa();const bodyParser =require('koa-bodyparser');//用来解析body的中间件let registerRouter=require('./registerRouter.js')()//路由注册;
app.use(bodyParser());//这个koa-bodyparser必须在router之前被注册到app对象上。
app.use(registerRouter);
console.log(__dirname,"__dirname")// 对于任何请求,app将调用该异步函数处理请求:
app.use(async(ctx, next)=>{
console.log(`Process ${ctx.request.method}${ctx.request.url}...`);awaitnext();});;// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');