-2

I'm a rookie in nodejs, and I'm learning Koa. I got some problem about this code.

const Koa = require('koa');
const app = new Koa();

app.use(async function(ctx, next) {
  await next();
  if (ctx.body || !ctx.idempotent) return ;
  ctx.status = 404;
});

What is the meaning of await next() and if statement after that ?

  • When you researched this and saerched for those keywords, what did you find? – dfundako Nov 19 '19 at 16:53
  • I can understand ctx.body is content of the page ,and I check idempotent method like Get, HEAD, PUT but I don't know the if statement consist of both – Chao Xin Huang Nov 20 '19 at 02:41

1 Answers1

0

This works like a "catch all" statement, reading in plain English:

  • wait for the request to be processed by other parts of the app (await next())
  • when done, check if the app responded with a body or the request does not require a response body
  • if none is true, return HTTP code 404 "Not Found"
Alex Pakka
  • 9,466
  • 3
  • 45
  • 69
  • Sorry, I'm not sure "the request does not require a response body" meaning – Chao Xin Huang Nov 20 '19 at 02:44
  • Koa treats 'GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE' as idempotent (https://developer.mozilla.org/en-US/docs/Glossary/Idempotent). If there is a body or a request is e.g. a POST, it will not return 404 – Alex Pakka Nov 20 '19 at 04:39
  • Think about it this way, POST in REST API terms usually means "create something". It makes no sense to return 404 if there is no reply. If you can't create it, return 400 or 500 or whatever. – Alex Pakka Nov 20 '19 at 04:42