koa

85 阅读1分钟

基本使用

const koa = require('koa');
const app = new koa();
app.use((ctx, next) => {
  console.log('hello worls1');
  next();
});
app.use((ctx, next) => {
  console.log('hello worls2');
  next();
});
app.use((ctx, next) => {
  console.log('hello worls3');
  next();
});
app.listen(3000, () => {
  console.log('服务端启动了');
});

路由

安装路由模块

npm install --save-dev koa-router

使用路由模块:

const koa=require("koa");
const app=new koa();
//require("koa-router")  返回的是函数  执行之后返回对象
const router=require("koa-router")();
let port = 8080;
let host = 'localhost';
app.use(async (ctx,next)=>{
    console.log(ctx.request.url);
    await next();
});

//get路由
router.get('/',async (ctx,next)=>{
    ctx.response.body="首页";
});
router.get('/login',async (ctx,next)=>{
    ctx.response.body="登录";
});


//路由和koa框架关联
app.use(router.routes());
//路由监听
app.listen(port, host, () => {
    console.log(`http://${host}:${port}`);
});

获取get路由值:

//koa-router url get传值
router.get("/user",async (ctx,next)=>{
    //get  传值   值在  query上面
    console.log(ctx.request.query);
    ctx.response.body="获取get 传值";
});

获取post路由值:

1,安装解析post的body解析模块
npm install --save-dev koa-bodyparser
//2ckoa-router url get传值

//post路由传值
router.post('/regest',async (ctx,next)=>{
    console.log(ctx.request.body);
    ctx.response.body="注册成功";
});


koa错误处理(中间件)

npm install koa-json-error

const error = require('koa-json-error')
//定制返回错误的数据格式
app.use(error({
    postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}))

ctx.throw(412, '先决条件失败:id大于数据长度')

//返回错误信息
{
    "message":"先决条件失败:id大于数据长度",
    "name":"PreconditionFailedError",
    "status":412
}