koa介绍

ctx.response. type = 'json' ;
app.use() 用来加载中间件
app. use (ctx => { ctx. body = 'Hello Koa' ; });
以"先进后出"(first-in-last-out)的顺序执行。
  1. 最外层的中间件首先执行。
  2. 调用next函数,把执行权交给下一个中间件。
  3. ...
  4. 最内层的中间件最后执行。
  5. 执行结束后,把执行权交回上一层的中间件。
  6. ...
  7. 最外层的中间件收回执行权之后,执行next函数后面的代码。
const one = ( ctx , next ) => { console . log ( '>> one' ); next (); console . log ( '<< one' ); } const two = ( ctx , next ) => {
console . log ( '>> two' ); next (); console . log ( '<< two' ); } const three = ( ctx , next ) => { console . log ( '>> three' ); next (); console . log ( '<< three' ); } app . use ( one ); app . use ( two ); app . use ( three );
有如下输出。
>> one >> two >> three << three << two << one
上面都是 同步的中间件 ,异步的需要加async
const main = async function ( ctx , next ) { ctx . response . type = 'html' ; ctx . response . body = await fs . readFile ( './demos/template.html' , 'utf8' ); }; app . use ( main );
上面代码中, fs.readFile 是一个异步操作,必须写成 await fs.readFile() ,然后中间件必须写成 async 函数。
上下文
请求
响应
async function doWork() { // 使用 async/await 的方式依次获取两个 JSON 文件 var result1 = await fetch('data1.json'); var result2 = await fetch('data2.json'); return { result1, result2 }; }
这个语法可以理解为:被 async 关键字标记的函数, 可以对其使用 await 关键字来暂停函数的执行直到异步操作结束
async function indexStep1 ( ctx , next ) { //逻辑处理第一部分 await next (); } async function indexStep2 ( ctx , next ) { //逻辑处理第二部分 await next (); } async function indexStep3 ( ctx , next ) { //逻辑处理第三部分 await ctx . render ( 'index' ); } router . get ( '/index' , indexStep1 , indexStep2 , indexStep3 );

同时实现get和post
router.all
Create routes with multiple HTTP methods using  router.register() :
app.register( '/' , [ 'get' , 'post' ], function * (next) { // ... });
Create route for all methods using  router.all() :
app.all( '/' , function * (next) { // ... });
获取参数
eventCenter?data1=leijh
var data = ctx.request.query.data || null;

转载于:https://www.cnblogs.com/elesos/p/8404909.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值