node.js开发框架--koa

一、安装

  • 生成配置文件:cnpm init --yes
  • koa框架:cnpm install --save-dev koa或者cnpm install --save-dev koa@2.0.0

二、koa入门

// 引入koa
const koa=require("koa");
// 创建koa对象,必须使用new,否则会报错
const app=new koa();
// 建立基本变量
let port=8080;
let host='localhost';
// 对于所有的http请求都会执行下面这个异步处理函数
// ctx是koa框架封装的一个对象,里面包含request和response两个参数
app.use(async (ctx,next)=>{
   console.log("http请求");
   // 继续向下执行,next是处理下一个异步处理函数
   await next();
   // 设置响应的类型和响应的数据
   // 设置Content-Type
   ctx.response.type="text/html";
   // 设置response的内容
   ctx.response.body="<h3>koa框架</h3>";
   // 相当于界面响应
   // ctx.body="首页";
});
// 监听端口
app.listen(port,host,()=>{
   console.log(`http://${host}:${port}`);
})
  • 其中,参数ctx是由koa传入的封装了request和response的变量,我们可以通过它访问request和response,next是koa传入的将要处理的下一个异步函数。
  • 上面的异步函数中,我们首先用await next();处理下一个异步函数,然后,设置response的Content-Type和内容。
  • 由async标记的函数称为异步函数,在异步函数中,可以用await调用另一个异步函数,这两个关键字将在ES7中引入。
  • 让我们再仔细看看koa的执行逻辑。核心代码是:
app.use(async (ctx, next) => {
   await next();
   ctx.response.type = 'text/html';
   ctx.response.body = '<h1>Hello, koa2!</h1>';
});
  • 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。
  • 我们可以对ctx操作,并设置返回内容。但是为什么要调用await next()?
    原因是koa把很多async函数组成一个处理链,每个async函数都可以做一些自己的事情,然后用await next()来调用下一个async函数。我们把每个async函数称为middleware,这些middleware可以组合起来,完成很多有用的功能。
  • middleware的顺序很重要,也就是调用app.use()的顺序决定了middleware的顺序。
  • 此外,如果一个middleware没有调用await next()会怎么办?答案是后续的middleware将不再执行了。
  • 最后注意ctx对象有一些简写的方法,例如ctx.url相当于ctx.request.url,ctx.type相当于ctx.response.type。

三、处理URL

  • 在hello-koa工程中,我们处理http请求一律返回相同的HTML,这样虽然非常简单,但是用浏览器一测,随便输入任何URL都会返回相同的网页。

1.处理URL基本方法

app.use(async ctx=>{
   // url和path都是指向的当前路径,但是url指的是全路径  path指的是路径
   let url=ctx.request.url;
   console.log(url);
   if(url=="/"){
       ctx.response.body="首页";
   }
   else if(url=="/login"){
       ctx.response.body="登录";
   }
});
  • 或者
// 处理url
app.use(async (ctx,next)=>{
   if(ctx.request.path=="/"){
       ctx.response.body="首页";
   }
   else{
       // 执行下一个异步处理函数
       await next();
   }
});
app.use(async (ctx,next)=>{
   if(ctx.request.path=="/login"){
       ctx.response.body="登录";
   }
   else{
       // 执行下一个异步处理函数
       await next();
   }
});
app.use(async (ctx,next)=>{
   if(ctx.request.path=="/regest"){
       ctx.response.body="注册";
   }
   else{
       // 执行下一个异步处理函数
       await next();
   }
});
  • 这么写是可以运行的,但是好像有点繁琐。
  • 应该有一个能集中处理URL的middleware,它根据不同的URL调用不同的处理函数,这样,我们才能专心为每个URL编写处理函数。

2.使用路由koa-router处理URL

  • 为了处理URL,我们需要引入koa-router这个middleware,让它负责处理URL映射。
  • 安装koa-router:cnpm install --save-dev koa-router
const koa=require("koa");
const app=new koa();
// require("koa-router")()返回的是函数,执行之后返回对象
const router=require("koa-router")();
// 引入koa-bodyparser
const bodyparser=require("koa-bodyparser");
// 把koa-bodyparser关联到koa框架
app.use(bodyparser());
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-router的url传值
router.get("/user",async (ctx,next)=>{
   // get传值,值在query上面
   console.log(ctx.request.query);
   ctx.response.body="获取get传值";
})

// post路由
// get路由,先到界面
router.get("/regest",async (ctx,next)=>{
   ctx.response.body=`
       <form action='/regest' method='post'>
           <input type='text' name='id'/>
           <button>注册</button>
       </form>
   `
});
// 表单提交post,传值获取使用koa-bodyparser
// 安装:cnpm install --save-dev koa-bodyparser
router.post('/regest',async (ctx,next)=>{
   console.log(ctx.request.body);
   ctx.response.body="注册成功";
});

// 路由和koa框架关联
app.use(router.routes());

// 监听端口
app.listen(port,host,()=>{
   console.log(`http://${host}:${port}`);
});

3.路由的模块化封装

  • app.js
const koa=require("koa");
const app=new koa();
const bodyparser=require("koa-bodyparser");
app.use(bodyparser());
let port=8080;
let host='localhost';
// 加载路由文件
let router=require("./router/routerMiddle");

// 关联路由
app.use(router());
app.listen(port,host,()=>{
   console.log(`http://${host}:${port}`);
});
  • routerMiddle.js
// 整理之后的路由文件
let index = require("./routes/index");
let login=require("./routes/login");
// 整理路由
let addController=(router,route)=>{
   for(let url in route){
       if(url.startsWith("GET ")){
           let path=url.substring(4);
           // 注册get路由
           router.get(path,route[url]);
       }
       else if(url.startsWith("POST ")){
           let path=url.substring(5);
           // 注册post路由
           router.post(path,route[url]);
       }
       else{
           console.log("404");
       }
   }
}
module.exports=()=>{
   let routes=Object.assign({},index,login),
   router=require("koa-router")();
   addController(router,routes);
   return router.routes();
}
  • router/index.js
// 首页路由
let f_index=async (ctx,next)=>{
   ctx.response.body="首页";
}
let f_regest=async (ctx,next)=>{
   ctx.response.body="表单注册";
}

// 模块导出
module.exports={
   'GET /':f_index,
   'POST /':f_regest
}
  • router/login.js
// 登陆界面的相关路由
let login_index=async (ctx,next)=>{
   ctx.response.body="登录界面";
}
let login_dologin=async (ctx,next)=>{
   ctx.response.body="登录成功";
}

// 模块导出
module.exports={
   'GET /login':login_index,
   'POST /dologin':login_dologin
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南初️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值