12月07, 2019

koa基础入门

最基本的一个例子

const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
  ctx.body = '123'
})
app.listen(3000, () => {
  console.log('服务开启成功')
})

浏览器打开http://localhost:3000/ 页面显示123

GET POST

const Koa = require('koa');
const Router = require('koa-router');
const bodyparser = require('koa-bodyparser'); //处理post传来的参数

const app = new Koa();
const router = new Router({
  prefix: '/api' //根路径增加字段
});
app.use(bodyparser());

//post请求 请求返回的都是请求的参数
router.post('/abc', (ctx, next) => {
  ctx.body = ctx.request.body;
});
//get请求
router.get('/test', (ctx, next) => {
  ctx.body = ctx.query;
});

app.use(router.routes());
app.use(router.allowedMethods());


app.listen(3000, () => {
  console.log('服务开启成功在3000端口');
});
<form action="http://localhost:3000/api/test" method="GET">
    <label for="title">
      <input type="text" id='title' name='title'>
    </label>
    <label for="password">
      <input type="password" id='password' name='password'>
    </label>
    <input type="submit" value="提交">
  </form>

cookie

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  if (ctx.url === '/canaan') {
    ctx.cookies.set(
      'name', 'canaan', {
        domain: 'localhost', //域名
        path: '/canaan', //路径
        maxAge: 24 * 60 * 60 * 1000, //有效时间 一天的毫秒
        expires: new Date('2019-12-31'), //失效时间
        httpOnly: false, //服务器可访问cookie
        overwrite: false //是否覆盖以前的同名cookie
      }
    );
    ctx.body = 'cookie success';
  } else {
    ctx.body = 'no cookie';
  }
});
app.listen(3000, () => {
  console.log('服务开启成功在3000端口');
});

浏览器访问http://localhost:3000/canaan 就会保存cookie

ejs

const Koa = require('koa');
const views = require('koa-views')
const path = require('path')
const app = new Koa();
app.use(views(path.join(__dirname, './views'), {
  extension: 'ejs'
}))
app.use(async ctx => {
  let title = 'nihao'
  await ctx.render('index', {
    title,
    list: [{
        name: 'zhangsan',
        age: '20'
      },
      {
        name: 'lisi',
        age: '20'
      },
    ]
  })
})
app.listen(3000, () => {
  console.log('服务开启成功在3000端口');
});
//views文件下的index.ejs
<body>
  <h1><%=title%></h1>
  <ul>
    <% for(let i=0;i<list.length;i++){ %>
    <li><%=list[i].name%>--<%=list[i].age%></li>
    <%}%>

  </ul>
</body>

本文链接:http://zzl.bzpwhite.cn/post/koa.html

-- EOF --

Comments