KOA-Views Suddenly Stop Working after First Route KOA-Views Suddenly Stop Working after First Route mongoose mongoose

KOA-Views Suddenly Stop Working after First Route


It looks like a http-server fault. Try to add an error handler.

Also I recomment to change error handling in code e.g.

route.put('/edit/:id', (ctx, next) => {    if (ctx.request.body.pw === process.env.pw){        Blog.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:True}, (err, result) => {         console.log(result);         })     } else {         console.log('wrong password');        }    return ctx.render('complete.njk');});

replace by

route.put('/edit/:id', (ctx, next) => {  // Early stop to avoid brace ladder  if (ctx.request.body.pw != process.env.pw)    ctx.throw('Env. wrong password'); // Pass request to error-handler  Blog.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:True}, (err, result) => {    if (err)                    ctx.throw('Db wrong password'); // or throw Error('Db wrong password');    ctx.render('complete.njk');  });}...server.use(route.routes());server.use(static('./public'));// Error handler: catch 'wrong password'-error here.app.on('error', (err, ctx) => {  console.error(err);  ctx.render('error.njk'); });

P.S. I use Express, not Koa. So maybe I made some mistakes.


Perhaps ctx.render requires async-await framing like below

route.get('/', async (ctx, next) => {    console.log('connected to root route');    console.log(ctx);    return Blog.find({}, (error, results) => {        console.log(results)        await ctx.render('index', {            posts: results        });        console.log('the view was rendered')    });});

I downloaded your git and made this changes. And it works :)


I never figured out was causing this behavior but I was able to fix and committed the working code to the github repository. After several attempts I could not get the koa-views library to work right so I gave up on it and switched to koa-nunjucks-2 and initialized it exactly as it says in their docs.

Unfortunately... the same problem kept happening till I changed the path to relative path with using path.join then koa-nunjucks-2 worked perfectly!

Why, or what was happening, I still have no idea. It probably has to do with unresolved promises under the hood but I'm not really sure.