On the problem of Certification of designated url in koa-router

The idea of

is like this

url =>  => (DONE) or (NEXT) => (403) or (DONE)

meta information that can be set up for routing is inspired in vue-router

auth: true

you can know whether permission is required for this url.

but what should I do when I see that koa-router doesn"t have such a similar thing?

< hr >

if it is vue-router "s idea, it should be like this

//  "/" 
{
    path: "/",
    name: "index",
    meta:{
        auth: true
    }
}

router.beforeEach((to, from, next) => {

    if ( to.meta.auth === true ){
        // next
        
        let miao = await XXX()
        
        if ( miao ===  ){
            next()
        }else{
            context.response.status = 403
            return
        }
        
    }else{
        next()
    }

})
Mar.10,2021

isn't that what middleware


writes a middleware before all router executes
if it matches the URL that needs authentication
the rest of the URL directly yield next / await next () .


answer it yourself. I've found a way.

router
    .('/userName', async context => await user.getName(context))

router
    .use(async (context, next) => await user.auth(context, next))

    .get('/userdata', async context => await user.getData(context))

as shown above, classify the routes according to the need for authentication and non-authentication, add a line of use to the route to be authenticated to use the authentication method, pass the next into the method, and control whether to run the following route in the auth method, otherwise it will return 403

Menu