What's the difference between koa2's ctx.state ctx.body?

is there any difference below?

controllers

async function get (ctx, next) {
    const res = await models.test.get()
    
    ctx.state.data = res.data
    /*******  ********/
    ctx.body = res.data
    
    await next()
}
module.exports = {
    get
}

routes

router.get("/", controllers.test.get, async (ctx, next) => {
    await ctx.render("test", {
        list: ctx.state.data.obj,
        /*******  ********/
        list: ctx.body.obj,
    })
})
Mar.06,2021

state is used to save data for middleware, while body is the final output


The recommended namespace for passing information through middleware and to your frontend views.

body remains the same as before, just talk about state .
Why is there state , because we have a lot of middleware to store some yesterday, such as login or permission verification, before that, we will report an error to a custom attribute of ctx , such as ctx.locals.isLogin , but we always have to write code like this

.
app.use(async ctx => {
    ctx.locals = ctx.locals || {};
});

now officially provides ctx.state status data for error reporting middleware.


to render the page on the koa server, you can use ctx.state to pass the value
for example:

ctx.state.username = '';
ctx.render('', {
    pageTitle: ''
});

so that you can get the value on the .ejs page

<input id="username" autocomplete="off" name="username" value="<%= username %>" placeholder="">

you can also get values in other rendering templates in different ways

  • How to learn Node? systematically

    I would like to ask you bosses about the problems in the direction of learning how to learn Node has always been my doubt. The blogs and tutorials I read on the Internet are all about learning several core modules of Nodejs (fs,path,event,buffer,http)...

    Mar.01,2021
  • Koa2 middleware or routing problems

    using koa2 s middleware, I want to implement an interceptor in order to perform some processing on all requests. The code is as follows: when visiting , the middleware is executed and and 1111 are printed at the terminal, but the page shows tha...

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b33e78-2bed7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b33e78-2bed7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?