Koa笔记
1.基本api
ctx.response.body = `**`; //设置访问页内容ctx.response.type = 'html'; //设置访问页类型,可选,html,json,text,xml
ctx.requset.accepts('html'); //判定客户端页面访问类型,返回boolean类型
ctx.url ==== '/index'; //获取客户端地址
ctx.request.path; //同上
ctx.method === 'GET'; //获取请求类型
ctx.query //获取get请求参数,对象形式
ctx.querystring //获取get请求参数,字符串形式
ctx.request.body //获取post请求参数,需加入下面两行代码
const bodyParser = require('koa-bodyparser'); //安装中间件
app.use(bodyParser()); //使用
所有以下js代码默认加入
const Koa=require('koa');
const app=new Koa();
app.listen(111);
2.路由
①const route = require('koa-route');
const main = ctx => {
ctx.body = `
<a href='/index'>点击</a>
`
}
const index = ctx => {
ctx.body = `
<h1>this is index</h1>
`
}
app.use(route.get('/', main));
app.use(route.get('/index', index));
②
const Router = require('koa-router');
const router = new Router({
prefix:'/hkj' //全局设置访问路径前缀
});
router.get('/', ctx => {
ctx.body = `
<a href='/index'>点击</a>
`
})
router.get('/index', ctx => {
ctx.body="<h1>this is index</h1>"
})
app.use(router.routes()); //加载路由
app.use(router.allowedMethods()); //出错时进行处理
③多路径前缀
const Router = require('koa-router');
const main = new Router();
main.get('/main', ctx => {
ctx.body = `
<h1>this is main</h1>
<a href='/pageTwo/index'>点击</a>
`
})
const index = new Router();
index.get('/index', ctx => {
ctx.body = `
<h1>this is index</h1>
`
})
const router = new Router();
router.use('/pageOne', main.routes(), main.allowedMethods());
router.use('/pageTwo', index.routes(), index.allowedMethods());
app.use(router.routes());
app.use(router.allowedMethods());
3.Cookie操作
ctx.cookies.set('key','value',option); //设置ctx.cookies.get('key'); //获取
const option={
domain:'127.0.0.1', //cookie所在域名
path:'/index', //cookie所在路径
maxAge:1000*60, //存在时长,单位毫秒
exprise:new Date('2018-5-18'), //截止失效时间
httpOnly:false, //是否只用于http请求
overwrite:false, //是否允许重写
}
4.ejs模板引擎
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= name %></h1>
<p>EJS Welcome to <%= age %></p>
</body>
</html>
const views=require('koa-views');
const path=require('path');
app.use(views(path.join(__dirname,../view/index.ejs),{
extension:'ejs'
}))
app.use(ctx=>{
const title='this is a title';
const name='hkj';
const age='21';
ctx.render('index',{
title,
name,
age
})
})