koa2

let Koa = require('koa');
let router = require('koa-router')();
let bodyParser = require('koa-bodyparser');
let app = new Koa();

// 异步函数
app.use(async (ctx, next) => {
    console.log(`${ctx.request.method}~~~~${ctx.request.url}`);
    await next();
});
app.use(async (ctx, next) => {
    let start = new Date().getTime();
    await next();
    const ms = new Date().getTime() - start; // 耗费时间
    console.log(`Time: ${ms}ms`); // 打印耗费时间
});
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello wrod!!!</h1>'
});
// 接口请求(办法愚蠢)
app.use(async (ctx, next) => {
    if (ctx.request.path === '/') {
        ctx.response.type = 'text/html'
        ctx.response.body = 'index page !!!!!!!!!'
    } else {
        await next();
    }
});
app.use(async (ctx, next) => {
    if (ctx.request.path === '/list') {
        ctx.response.type = 'text/html'
        ctx.response.body = '<ul><li>1</li><li>2</li><li>3</li></ul>'
    } else {
        await next();
    }
});
app.use(async (ctx, next) => {
    if (ctx.request.path === '/error') {
        ctx.response.type = 'text/html'
        ctx.response.body = 'notfund 404 哥们你找错人了吧'
    } else {
        await next();
    }
});
// 接口请求 (路由)router
app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
});
router.get('/', async (ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
});
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>Hello, ${name}!</h1>`
});
// 模拟登陆接口
// bodyParser 解析post数据
app.use(bodyParser());
router.get('/', async (ctx, next) => {
    ctx.response.body = `<h1>Index</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="koa"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
});
router.post('/signin', async (ctx, next) => {
    var name = ctx.request.body.name || '',
        password = ctx.request.body.password || '';
    console.log(`signin with name: ${name}, password: ${password}`);
    if (name === 'koa' && password === '12345') {
        ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
    } else {
        ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
    }
});
app.use(router.routes());
app.listen(9696);
console.log('app started at port 3000...')

  

原文地址:https://www.cnblogs.com/dekui/p/10445788.html