如何在Koajs的ejs模板中显示Flash / Toast消息?

时间:2019-05-12 13:04:12

标签: node.js ejs koa

我想使用ejs在koa视图中显示Flash / Toast消息。

如何定义全局变量?我收到的成功消息未定义。

我已在视图模板中添加了partials / _messages.html,单击按钮后,我想显示该即时消息。

index.js

const Koa = require('koa');
const bodyParser = require('koa-body');
const logger = require('koa-morgan')
const mongoose = require('mongoose');
const path = require('path');
const render = require('koa-ejs');
const Router = require('koa-router'); 
const session = require('koa-generic-session');
const flash = require('koa-better-flash');

const router = new Router();
const app =  module.exports = new Koa();

app.keys = [ 'keys' ];
app.use(session());
app.use(flash());
app.use(router.routes());
app.use(votes.routes()).use(votes.allowedMethods());


router.post('/messages', (ctx, next) => {
  // you can also pass an array of messages:
  // ctx.flash('info', [ 'hi', 'hello', 'good morning' ]);
  console.log('here');
  ctx.flash('info', 'hello world');
  ctx.flash('success_msg', 'hello world');
  ctx.status = 200;
});

router.get('/messages', ctx => {
  // to get all messages by type simply call `ctx.flash()`
  ctx.body = ctx.flash();
  // outputs: [ 'hello world ']
});



app.use( ctx => {
  ctx.success_msg = ctx.flash('success_msg');
});

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

部分路线

router.post('/votes/managervote', castManagerVote);
async function castManagerVote (ctx) {
  console.log(ctx.request.body);
  let vote = new Vote();
  vote.vote_category = 'Hiring manager';
  vote.incoming_vote = ctx.request.body.incoming_vote; 
  await vote.save()
          .then(data=> {
            ctx.flash('success_msg', 'ManagerDone');
            ctx.redirect('/votes');
          });
}

0 个答案:

没有答案