profile
viewpoint

Ask questionsMiddleware not working when using a router

I placed middleware after a router and it never gets called for some reason. I want to log the status of a response. Below is the code used.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

const router = new Router();
router.get("/", async (context, next) => {
  context.response.body = "hello world";
  await next();
});

app.use(router.routes());
app.use(router.allowedMethods());

app.use(async (context, next) => {
  console.log(context.response.toServerResponse().status);
  await next();
});

await app.listen({ port: 8000 });
oakserver/oak

Answer questions kitsonk

by doing context.response.toServerResponse().status you are consuming the response which means it can't be sent to the server. I need to make that more hidden, because it shouldn't be used by middleware. If you want to know what the status of the response is at the time... context.response.status, but you also want to put the next() before hand.

If you are depending on automatic body processing though, which will set the status when the body is processed, then that isn't quite do-able at the moment, because the status isn't set until after all the middleware has run.

useful!

Related questions

No questions were found.
Github User Rank List