V
V
Vladimir2018-03-28 09:20:57
Node.js
Vladimir, 2018-03-28 09:20:57

How to redirect to koa?

For rendering I use Pug.
Option 1:

app.use(async (ctx, next) => {
    if (ctx.status === 404) {// always is 404
      ctx.redirect('/node/404');
    }
    await next();
  });

A middleware is used to catch missing pages, but Koa always has a 404 status unless manually changed. Accordingly, the redirect will occur from any page. But! The redirected page is not rendered at all, and nginx (it's for static) gives "this page unreachable".
Option 2:
const router = new Router({prefix: 'auth'});
router.post('/signin', authController.signIn);

async signIn(ctx) {
   // проверяю параметры и по их результатам делаю редирект

    ctx.redirect('/node');
  },

In this case, instead of a redirect, I get in the response body the html of the rendered page, to which, in fact,
the redirect should take place (as if I was doing ctx.body = {data: pug.renderFile(pattern)})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question