1,Koa异步处理Async、Await、和Promise
async是让方法异步,在终端node执行获取promise对象
await等待异步方法执行完成,注:await必须在async方法中才可以使用。
2,Koa路由
在Koa中我们可以通过koa-router完成对路由的处理
1)koa-router的下载
npm install --save koa-router
2)koa-router的引入
const Koa=require('koa');
const router=require('koa-router')();
const app=new Koa();
router.get('/',function(ctx,next){
ctx.body="hello koa"
})
app.use(router.routes());
//作用:启动路由
app.use(router.allowedMethods());
// 作用: 这是官方文档的推荐用法,我们可以 看到 router.allowedMethods()用在了路由匹配 router.routes()之后,所以在当所有 路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
app.listen(3000,()=>{ console.log('starting at port 3000'); });
3,Koa路由get传值
在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。
query:返回的是格式化好的参数对象。
querystring:返回的是请求字符串。
router.get('/news,(ctx,next)=>{ let url =ctx.url;
//从 request 中获取 GET 请求
let request =ctx.request;
let req_query = request.query;
let req_querystring = request.querystring;
//从上下文中直接获取
let ctx_query = ctx.query;
let ctx_querystring = ctx.querystring;
ctx.body={
url, req_query,
req_querystring,
ctx_query,
ctx_querystring }
});
4,Koa动态路由
//请求方式 http://域名/product/123 router.get('/product/:aid',async (ctx)=>{ console.log(ctx.params); //{ aid: '123' }
//获取动态路由的数据
ctx.body='这是商品页面';
});
5,Koa的中间件
1)什么是中间件:
中间件就是路由匹配之前或匹配路由完成一系列的操作,它的功能包括以下几点
*1,执行任何代码
*2修改请求和响应请求
*3终结请求-响应请求
*4调用堆和栈中的下一个中间件
2)应用级中间件
//
app.use(async (ctx,next)=>{
console.log(new Date());
await next();
})
3)路由中间件
router.get('/', async(ctx, next)=>{
console.log(1) next()
})
router.get('/', function (ctx) {
ctx.body="Hello koa";
})
4)第三方中间件
const static = require('koa-static');
const staticPath = './static'; app.use(static(
path.join( __dirname, staticPath)
))
const bodyParser = require('koa-bodyparser'); app.use(bodyParser());
6,Koa Cookie的使用
1)什么是cookie
cookie 是保存在浏览器中的数据可以 让我们在同一个浏览器访问同一个域名时共享的数据(cookie)
2)Koa中设置cookie的值
ctx.cookies.set(name, value, [options])
3)Koa中获取Cookie的值
ctx.cookies.get('name');
4)Koa中设置中文Cookie
new Buffer('你好Koa').toString('base64');//转换成base64字符串,
new Buffer('base64字符串', 'base64').toString()//还原