Answer the question
In order to leave comments, you need to log in
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');
});
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
});
Answer the question
In order to leave comments, you need to log in
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');
}
});
userRouter.get('/settings', async (ctx) => {
await ctx.render('settings',{message: ctx.session.messages});
});
app.use(async (ctx,next)=>{
if(!ctx.session.messages) ctx.session.messages = [];
await next();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question