当前位置: 首页 > 后端技术 > Node.js

Koa.js学习笔记

时间:2023-04-04 00:37:01 Node.js

1.简单的小例子constKoa=require('koa');//引入Koa.jsconstapp=newKoa();//实例化Koa对象constmain=ctx=>{//main函数用来设置ctx.response.bodyctx.response.body='HelloWorld';//context.response.body是发送给用户的消息}app.use(main);//加载主函数app.listen(3000);//创建一个服务器,监听3000端口2.HTTPResponse的类型//Koa默认返回类型是text/plain,如果要返回其他类型的内容,可以先用ctx.request.accepts判断一下,what客户端要接受的数据(根据HTTPRequest的Accept字段),然后使用ctx.response.type指定返回类型constKoa=require('koa');constapp=newKoa();constmain=ctx=>{if(ctx.require.accepts('xml')){ctx.response.type='xml';ctx.response.body='Hello'}elseif(ctx.require.accepts('json')){ctx.response.type='json';ctx.response.body={data:'你好'};}elseif(ctx.require.accepts('html')){ctx.response.type='html';ctx.response.body='

你好

'}else{ctx.response.type='text';ctx.response.body='你好';}}应用程序。使用(主要);app.listen(3000);3。路由(封装koa-route模块)constKoa=require('koa');constapp=newKoa();constroute=require('koa-route');constabout=ctx=>{ctx.response.type='html';//发送给客户端的消息类型为htmlctx.response.body='转到首页'//发送的内容}constmain=ctx=>{ctx.response.type='html';ctx.response.body='

我是首页

'}app.use(route.get('/',main));//客户端访问根路径时,返回主函数app.use(route.get('/about',about));app.listen(3000);4、静态资源//如果网站提供静态资源(图片、字体、样式表、脚本...),不需要为它们一一写路由,koa-static模块封装了这部分请求constpath=require('path');constserve=require('koa-static');constmain=serve(path.join(__dirname));app.use(main);5.Redirection//在某些情况下,服务器需要重定向(redirect)访问请求例如,用户登录后,将其重定向到登录前的页面。ctx.response.redirect()方法可以发出302重定向,引导用户到另一条路线。constKoa=require('koa');constapp=newKoa();constroute=require('koa-route');constredirect=ctx=>{ctx.response.redirect('/');//将用户重定向到主页}constmain=ctx=>{ctx.response.type='html';ctx.response.body='首页';}app.use(route.get('/redirect',redirect));app.use(route.get('/',main));app.use(main);app.listen(3000);6、中间件1、打印日志(Logger函数):constmain=ctx=>{cxt.response.body='Hello';console.log(`${Date.now()}${ctx.request.method}${ctx.request.url}`)//1502144902843GET/}2、什么是中间件?//基本上Koa的所有功能都是通过中间件来实现的。//代码中的logger和main函数被称为中间件(middleware),因为它处于HTTPRequest和HTTPResponse的中间,用来实现某种中间功能。app.use()用于加载中间件//每个中间件默认接受两个参数,第一个参数是Context对象,第二个参数是next函数。只要调用下一个函数,就可以把执行权交给下一个中间件constlogger=(ctx,next)=>{console.log(`${Date.now()}${ctx.request.method}${ctx.request.url}`)}constmain=ctx=>{ctx.response.body='

你好

';}应用程序使用(记录器);应用程序使用(主要);应用程序。听(3000);3、异步中间件constfs=require('fs.promised');constKoa=require('koa');constapp=newKoa();constmain=asyncfunction(ctx,next){//async表示函数是异步函数(ES6语法)ctx.response.type='html';ctx.response.body=awaitfs.readFile('./demos/template.html','utf8')}app.use(main);app.listen(3000);4.中间件的组合//koa-compose模块可以将多个中间件合成一个constKoa=require('koa');constapp=newKoa();constcompose=require('koa-compose');constlogger=(ctx,next)=>{console.log(`${Date.now()}${ctx.request.method}${ctx.request.url}`);next()}constmain=ctx=>{ctx.response.body='你好';}constmiddlewares=compose([logger,main]);应用程序使用(中间件);7、错误处理1、抛出500错误、404错误constmain=ctx=>{ctx.response.status=404;//等于:ctx.throw(404)ctx.response.body='找不到页面';}2.处理错误的中间件//main函数抛出错误,被处理函数捕获consthandler=asyncfunction(ctx,next){tr{awaitnext();}catch(err){ctx.response.status=err.statusCode||err.status||500;ctx.response.body={message:err.message}}}constmain=ctx=>{ctx.throw(500);}应用程序使用(处理程序);应用程序使用(主要);3.错误事件监听//一旦运行过程中出现错误,Koa会触发错误事件监听这个事件,也可以处理错误constmain=ctx=>{ctx.throw(500);}app.on('error',(err,ctx)=>{console.error('Servererror',err)})4.释放error事件//如果错误被try...catch捕获,不会触发错误事件。这时候必须调用ctx.app.emit()手动释放error事件才能使监听函数生效consthandler=async(ctx,next)=>{try{awaitnext();}catch(err){ctx.response.status=err.statusCode||错误状态||500;ctx.response.type='html';ctx.response.body='

有问题,请联系管理员。

';ctx.app.emit('错误',err,ctx);}};constmain=ctx=>{ctx.throw(500);};app.on('error',function(err){console.log('记录错误',err.message);console.log(err);});八、WebApp函数1、Cookies//ctx.cookies.get('cookieName')用于读取Cookie//ctx.cookies.set('cookieName',value)用来写Cookieconstmain=ctx=>{//你会看到1次浏览刷新一次页面,变成2viewsconstn=Number(ctx.cookies.get('view')||0)+1;ctx.cookies.set('view',n);ctx.response.body=n+'view';}2.//koa-body模块的形式可以用来从POST请求数据体中提取键值对constKoa=require('koa');constkoaBody=require('koa-body');constapp=newKoa();constmain=asyncfunction(ctx){constbody=ctx.request.body;if(!body.name){ctx.throw(400,'.namerequired');}ctx.body={名称:body.name};};app.use(koaBody());应用程序使用(主要);app.listen(3000);3.文件上传constos=require('os');constpath=require('路径');constkoaBody=require('koa-body');constmain=asyncfunction(ctx){consttmpdir=os.tmpdir();const文件路径=[];常量文件=ctx.request.body.files||{};for(letkeyinfiles){constfile=files[key];constfilePath=path.join(tmpdir,file.name);constreader=fs.createReadStream(file.path);constwriter=fs.createWriteStream(文件路径);读者.管道(作者);filePaths.push(文件路径);}ctx.body=文件路径;};app.use(koaBody({multipart:true}));参考阮一峰的博客