notfound.js 809 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. module.exports = options => {
  3. return async function notfound(ctx, next) {
  4. await next();
  5. if (ctx.status !== 404 || ctx.body) {
  6. return;
  7. }
  8. // set status first, make sure set body not set status
  9. ctx.status = 404;
  10. if (ctx.acceptJSON) {
  11. ctx.body = {
  12. message: 'Not Found',
  13. };
  14. return;
  15. }
  16. const notFoundHtml = '<h1>404 Not Found</h1>';
  17. // notfound handler is unimplemented
  18. if (options.pageUrl && ctx.path === options.pageUrl) {
  19. ctx.body = `${notFoundHtml}<p><pre><code>config.notfound.pageUrl(${options.pageUrl})</code></pre> is unimplemented</p>`;
  20. return;
  21. }
  22. if (options.pageUrl) {
  23. ctx.realStatus = 404;
  24. ctx.redirect(options.pageUrl);
  25. return;
  26. }
  27. ctx.body = notFoundHtml;
  28. };
  29. };