I
I
Ilya2018-11-13 14:52:19
JavaScript
Ilya, 2018-11-13 14:52:19

How to display information to the user in koajs?

For example, there is this code:

let userRouter = new Router({prefix: '/user'});//koa-router
userRouter.use(authCheck);

userRouter.get('/settings', async (ctx) => {
    await ctx.render('settings',{message: '???'});//Откуда брать сообщение, если это уже другой ctx?
});
userRouter.post('/settings', async (ctx) => {
    const data = ctx.request.body;
    if(!data.email || !data.email.length) ctx.message = 'Введите почту!';
    if(!data.password || !data.password .length) ctx.message = 'Введите пароль!';
    await ctx.redirect('/user/settings');
});

How to display information to the user if he is redirected from this page?
Is it correct to render in two places, for example, if an error occurs, render the same page in a post request, like this:
userRouter.get('/settings', async (ctx) => {
    await ctx.render('settings',{message: false});//#1
});
userRouter.post('/settings', async (ctx) => {
    const data = ctx.request.body;
    let err = false;
    if(!data.email || !data.email.length) err = 'Введите почту!';
    if(!data.password || !data.email.password) err = 'Введите пароль!';
    
    await ctx.render('settings', {message: err});//#2
});

If this is a normal solution, then how to display information, for example, about a successful login, there should clearly be a redirect from the authorization page.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2018-11-13
@Mr_Epic

Messages can be saved using koa-session .
For example:

userRouter.post('/settings', async (ctx) => {
    const data = ctx.request.body;
    if(!data.email || !data.email.length) {
        ctx.session.messages.push('Введите почту!');
        ctx.redirect('/user/settings');
    }
});

You can output information like this:
userRouter.get('/settings', async (ctx) => {
    await ctx.render('settings',{message: ctx.session.messages});
});

Also, do not forget about the first visit, when messages do not exist yet:
app.use(async (ctx,next)=>{
    if(!ctx.session.messages) ctx.session.messages = [];
    await next();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question