Koa2 Express middleware and contrast

koa2 Middleware

koa2 through middleware async awaitimplemented, execution order is a middleware "onion ring" model.

By next link function when a call between the middleware Middleware next(), the next will hand over control of the middleware, the middleware is not executed until the next next()post, we will be folded along the road, turn right control before switching to a middleware.

Figure:


image


koa2 middleware examples

app.js:

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


// logger
app.use(async (ctx, next) => {
    console.log('第一层 - 开始')
    await next();
    const rt = ctx.response.get('X-Response-Time');
    console.log(`${ctx.method} ----------- ${ctx.url} ----------- ${rt}`);
    console.log('第一层 - 结束')
});


// x-response-time
app.use(async (ctx, next) => {
    console.log('第二层 - 开始')
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
    console.log('第二层 - 结束')
});


// response
app.use(async ctx => {
    console.log('第三层 - 开始')
    ctx.body = 'Hello World';
    console.log('第三层 - 结束')
});


app.listen(3000);

After performing app.js, browser to access HTTP: // localhost: 3000 / text , the console output:

第一层 - 开始
第二层 - 开始
第三层 - 开始
第三层 - 结束
第二层 - 结束
打印第一次执行的结果: GET -------- /text ------ 4ms
第一层 - 结束

koa2 middleware application

Here is a login authentication middleware:

loginCheck.js:

module.exports = async (ctx, next) => {
    if (ctx.session.username) {
        // 登陆成功,需执行 await next(),以继续执行下一步
        await next()
        return
    }
    // 登陆失败,禁止继续执行,所以不需要执行 next()
    ctx.body = {
        code: -1,
        msg: '登陆失败'
    }
}

Use loginCheck.js in the delete operation:

router.post('/delete', loginCheck, async (ctx, next) => {
    const author = ctx.session.username
    const id = ctx.query.id
    // handleDelete() 是一个处理删除的方法,返回一个 promise
    const result = await handleDelete(id, author)

    if (result) {
        ctx.body = {
            code: 0,
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '删除失败'
        }
    }
})

express middleware

The difference is that the koa2 middleware, the middleware Express performed one by one sequentially, in response to the write response will usually last a middleware

main feature:

  • app.use used to register middleware
  • Encounter http request, according to the path and method to determine what triggered middleware
  • Achieve next mechanism that will pass on a middleware next next trigger a middleware

Examples express middleware

const express = require('express')

const app = express()

app.use((req, res, next) => {
    console.log('第一层 - 开始')
    setTimeout(() => {
        next()
    }, 0)
    console.log('第一层 - 结束')
})

app.use((req, res, next) => {
    console.log('第二层 - 开始')
    setTimeout(() => {
        next()
    }, 0)
    console.log('第二层 - 结束')
})

app.use('/api', (req, res, next) => {
    console.log('第三层 - 开始')
    res.json({
        code: 0
    })
    console.log('第三层 - 结束')
})

app.listen(3000, () => {
    console.log('server is running on port 3000')
})

After performing app.js, browser to access HTTP: // localhost: 3000 / API , the console output:

第一层 - 开始
第一层 - 结束
第二层 - 开始
第二层 - 结束
第三层 - 开始
第三层 - 结束

Since each of the above intermediate in the next () is executed asynchronously, the result is printing lines of output lines.

If you cancel the above next () is executed asynchronously, directly as follows:

const express = require('express')

const app = express()

app.use((req, res, next) => {
    console.log('第一层 - 开始')
    next()
    console.log('第一层 - 结束')
})

app.use((req, res, next) => {
    console.log('第二层 - 开始')
    next()
    console.log('第二层 - 结束')
})

app.use('/api', (req, res, next) => {
    console.log('第三层 - 开始')
    res.json({
        code: 0
    })
    console.log('第三层 - 结束')
})

app.listen(3000, () => {
    console.log('server is running on port 3000')
})

After performing app.js, browser to access HTTP: // localhost: 3000 / API , the console output:

第一层 - 开始
第二层 - 开始
第三层 - 开始
第三层 - 结束
第二层 - 结束
第一层 - 结束

Visible, express middleware can also form "onion rings" model, but generally will not do so in express, because express the response in the last general middleware, other middleware, so the next () after the code that affects less than final result.

express middleware application

Here is a login authentication middleware:

loginCheck.js:

module.exports = (req, res, next) => {
    if (req.session.username) {
        // 登陆成功,需执行 next(),以继续执行下一步
        next()
        return
    }
    // 登陆失败,禁止继续执行,所以不需要执行 next()
    ctx.body = {
        code: -1,
        msg: '登陆失败'
    }
} 

Use loginCheck.js in the delete operation:

router.post('/delete', loginCheck, (req, res, next) => {
    const author = req.session.username
    const id = req.query.id
    // handleDelete() 是一个处理删除的方法,返回一个 promise
    const result = handleDelete(id, author)

    return result.then(val => {
        if (val) {
            ctx.body = {
                code: 0,
                msg: '删除成功'
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '删除失败'
            }
        }
    })
}) 

Guess you like

Origin www.cnblogs.com/cckui/p/10991062.html
Recommended