简介:koa是基于node.js平台的web开发框架,致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。
安装的方法:
npm i koa
使用方法:
安装完了之后然后就是引包和创建对象:
引包:const koa = require("koa");
引完包之后就是创建对象let app = new koa();
我们来举个万年不变的hello word例子来看下koa框架
const koa = require("koa");
let app = new koa();
app.use((ctx,next)=>{
next();
ctx.response.body = `<h1>hello koa</h1>`
});
app.listen(3001);
app.use的中间件里有两个形参:ctx是个对象,里面有两个对象,分别是request()对象和response()对象,可以用来请求和响应。next()是一个函数,执行了之后才能执行后面的代码,不写的话后面的代码就无法执行。
- async函数和await的使用
async是异步函数,await必须配合async使用
const koa = require("koa");
let app = new koa();
app.use(async (ctx,next)=>{
await next();
ctx.response.body = `<h1>hello koa</h1>`
});
app.listen(3001);
koa-router包:配合koa使用
安装:npm install koa-router --save
安装完之后就是引包:const koaRouter = require("koa-router")();
.get()路由:
const koa = require("koa");
const koaRouter = require("koa-router")();
let app = new koa();
koaRouter.get("/",async (cxt,next)=>{
cxt.body = `index page`;
await next();
});
app.listen(3003);
app.use(koaRouter.routes());
cxt.params获取动态路由:返回的是一个对象。JSON.stringify()装换成json格式
koaRouter.get("/hello/:name",async (cxt,next)=>{
let name = JSON.stringify(cxt.params);
cxt.body = `${name}`;
});