status-handlers.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. const he = require('he');
  3. // not modified
  4. exports['304'] = (res) => {
  5. res.statusCode = 304;
  6. res.end();
  7. };
  8. // access denied
  9. exports['403'] = (res, next) => {
  10. res.statusCode = 403;
  11. if (typeof next === 'function') {
  12. next();
  13. } else if (res.writable) {
  14. res.setHeader('content-type', 'text/plain');
  15. res.end('ACCESS DENIED');
  16. }
  17. };
  18. // disallowed method
  19. exports['405'] = (res, next, opts) => {
  20. res.statusCode = 405;
  21. if (typeof next === 'function') {
  22. next();
  23. } else {
  24. res.setHeader('allow', (opts && opts.allow) || 'GET, HEAD');
  25. res.end();
  26. }
  27. };
  28. // not found
  29. exports['404'] = (res, next) => {
  30. res.statusCode = 404;
  31. if (typeof next === 'function') {
  32. next();
  33. } else if (res.writable) {
  34. res.setHeader('content-type', 'text/plain');
  35. res.end('File not found. :(');
  36. }
  37. };
  38. exports['416'] = (res, next) => {
  39. res.statusCode = 416;
  40. if (typeof next === 'function') {
  41. next();
  42. } else if (res.writable) {
  43. res.setHeader('content-type', 'text/plain');
  44. res.end('Requested range not satisfiable');
  45. }
  46. };
  47. // flagrant error
  48. exports['500'] = (res, next, opts) => {
  49. res.statusCode = 500;
  50. res.setHeader('content-type', 'text/html');
  51. const error = String(opts.error.stack || opts.error || 'No specified error');
  52. const html = `${[
  53. '<!doctype html>',
  54. '<html>',
  55. ' <head>',
  56. ' <meta charset="utf-8">',
  57. ' <title>500 Internal Server Error</title>',
  58. ' </head>',
  59. ' <body>',
  60. ' <p>',
  61. ` ${he.encode(error)}`,
  62. ' </p>',
  63. ' </body>',
  64. '</html>',
  65. ].join('\n')}\n`;
  66. res.end(html);
  67. };
  68. // bad request
  69. exports['400'] = (res, next, opts) => {
  70. res.statusCode = 400;
  71. res.setHeader('content-type', 'text/html');
  72. const error = opts && opts.error ? String(opts.error) : 'Malformed request.';
  73. const html = `${[
  74. '<!doctype html>',
  75. '<html>',
  76. ' <head>',
  77. ' <meta charset="utf-8">',
  78. ' <title>400 Bad Request</title>',
  79. ' </head>',
  80. ' <body>',
  81. ' <p>',
  82. ` ${he.encode(error)}`,
  83. ' </p>',
  84. ' </body>',
  85. '</html>',
  86. ].join('\n')}\n`;
  87. res.end(html);
  88. };