koa 初体验

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

// 1. 中间件的演示

// app.use(async (ctx, next) => {
//     console.log(`${ctx.request.method} ${ctx.request.url}`);
//     await next();
// })

// app.use(async (ctx, next) => {
//     const 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.type = 'text/html';
//     ctx.body = '<h1>Hello, Koa2!</h1>';
// })


// 2. 设置不同的路由演示
// app.use(async (ctx, next) => {
//     if(ctx.url === '/') ctx.body = 'index page'
//     else await next();
// })

// app.use(async (ctx, next) => {
//     if(ctx.url === '/test') ctx.body = 'test page'
//     else await next();
// })

// app.use(async (ctx, next) => {
//     if(ctx.url === '/error') ctx.body = 'error page'
//     else await next();
// })

// 3. 使用koa-router 改进2的代码
// npm i koa-router
// const router = require('koa-router')();// 注意这里是一个函数


// app.use(async (ctx, next) => {
//     console.log(`Process ${ctx.method} ${ctx.url}...`);
//     await next();
// });


// router.get('/hello/:name', async (ctx, next) => {
//     let name = ctx.params.name;
//     ctx.body = `<h1>Hello, ${name} !</h1>`
// })

// router.get('/', async (ctx, next) => {
//     ctx.body = `<h1> Index </h1>`
// })


// app.use(router.routes());//将router.routes()注册到app
//注意,这句话一般是要放到最后的,因为这句话之后的中间件都不会执行。

// 4. 使用 koa-router 的 post 请求中间件问题
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');// npm i koa-bodyparser

app.use(bodyParser());

router.get('/', async (ctx, next) => {
    ctx.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) => {
    let name = ctx.request.body.name || '';
    let password  = ctx.request.body.password || '';
    console.log(`signin with name: ${name} , password: ${password}`);
    if(name === 'koa' && password === '12345') {
        ctx.body = `<h1> Welcome, ${name}</h1>`;
    }
    else {
        ctx.body = `<h1> Login failed! </h1>
        <p> <a href='/' >Try again </a> </p>`
    }
})


app.use(router.routes());

app.listen(3000)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值