index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. 'use strict';
  2. /**
  3. * CORS middleware
  4. *
  5. * @param {Object} [options]
  6. * @return {GeneratorFunction}
  7. * @api public
  8. */
  9. module.exports = function getMiddleware(options) {
  10. options = options || {};
  11. var defaults = {
  12. origin: true,
  13. methods: 'GET,HEAD,PUT,POST,DELETE'
  14. };
  15. // Set defaults
  16. for (var key in defaults) {
  17. if (!options.hasOwnProperty(key)) {
  18. options[key] = defaults[key];
  19. }
  20. }
  21. // Set expose
  22. if (Array.isArray(options.expose)) {
  23. options.expose = options.expose.join(',');
  24. }
  25. // Set maxAge
  26. if (typeof options.maxAge === 'number') {
  27. options.maxAge = options.maxAge.toString();
  28. } else {
  29. options.maxAge = null;
  30. }
  31. // Set methods
  32. if (Array.isArray(options.methods)) {
  33. options.methods = options.methods.join(',');
  34. }
  35. // Set headers
  36. if (Array.isArray(options.headers)) {
  37. options.headers = options.headers.join(',');
  38. }
  39. return function* cors(next) {
  40. /**
  41. * Access Control Allow Origin
  42. */
  43. var origin;
  44. if (typeof options.origin === 'string') {
  45. origin = options.origin;
  46. } else if (options.origin === true) {
  47. origin = this.get('origin') || '*';
  48. } else if (options.origin === false) {
  49. origin = options.origin;
  50. } else if (typeof options.origin === 'function') {
  51. origin = options.origin(this.request);
  52. }
  53. if (origin === false) return;
  54. this.set('Access-Control-Allow-Origin', origin);
  55. /**
  56. * Access Control Expose Headers
  57. */
  58. if (options.expose) {
  59. this.set('Access-Control-Expose-Headers', options.expose);
  60. }
  61. /**
  62. * Access Control Max Age
  63. */
  64. if (options.maxAge) {
  65. this.set('Access-Control-Max-Age', options.maxAge);
  66. }
  67. /**
  68. * Access Control Allow Credentials
  69. */
  70. if (options.credentials === true) {
  71. this.set('Access-Control-Allow-Credentials', 'true');
  72. }
  73. /**
  74. * Access Control Allow Methods
  75. */
  76. this.set('Access-Control-Allow-Methods', options.methods);
  77. /**
  78. * Access Control Allow Headers
  79. */
  80. var headers;
  81. if (options.headers) {
  82. headers = options.headers;
  83. } else {
  84. headers = this.get('access-control-request-headers');
  85. }
  86. if (headers) {
  87. this.set('Access-Control-Allow-Headers', headers);
  88. }
  89. /**
  90. * Returns
  91. */
  92. if (this.method === 'OPTIONS') {
  93. this.status = 204;
  94. } else {
  95. yield next;
  96. }
  97. };
  98. };