koa笔记

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
    })
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值