You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1 KiB

  1. /**
  2. * Module dependencies.
  3. */
  4. var Polling = require('./polling');
  5. var Transport = require('../transport');
  6. var debug = require('debug')('engine:polling-xhr');
  7. /**
  8. * Module exports.
  9. */
  10. module.exports = XHR;
  11. /**
  12. * Ajax polling transport.
  13. *
  14. * @api public
  15. */
  16. function XHR(req){
  17. Polling.call(this, req);
  18. }
  19. /**
  20. * Inherits from Polling.
  21. */
  22. XHR.prototype.__proto__ = Polling.prototype;
  23. /**
  24. * Overrides `onRequest` to handle `OPTIONS`..
  25. *
  26. * @param {http.ServerRequest}
  27. * @api private
  28. */
  29. XHR.prototype.onRequest = function (req) {
  30. if ('OPTIONS' == req.method) {
  31. var res = req.res;
  32. var headers = this.headers(req);
  33. headers['Access-Control-Allow-Headers'] = 'Content-Type';
  34. res.writeHead(200, headers);
  35. res.end();
  36. } else {
  37. Polling.prototype.onRequest.call(this, req);
  38. }
  39. };
  40. /**
  41. * Frames data prior to write.
  42. *
  43. * @api private
  44. */
  45. XHR.prototype.doWrite = function(data){
  46. // explicit UTF-8 is required for pages not served under utf
  47. var isString = typeof data == 'string';
  48. var contentType = isString
  49. ? 'text/plain; charset=UTF-8'
  50. : 'application/octet-stream';
  51. var contentLength = '' + (isString ? Buffer.byteLength(data) : data.length);
  52. var headers = {
  53. 'Content-Type': contentType,
  54. 'Content-Length': contentLength
  55. };
  56. // prevent XSS warnings on IE
  57. // https://github.com/LearnBoost/socket.io/pull/1333
  58. var ua = this.req.headers['user-agent'];
  59. if (ua && (~ua.indexOf(';MSIE') || ~ua.indexOf('Trident/'))) {
  60. headers['X-XSS-Protection'] = '0';
  61. }
  62. this.res.writeHead(200, this.headers(this.req, headers));
  63. this.res.end(data);
  64. };
  65. /**
  66. * Returns headers for a response.
  67. *
  68. * @param {http.ServerRequest} request
  69. * @param {Object} extra headers
  70. * @api private
  71. */
  72. XHR.prototype.headers = function(req, headers){
  73. headers = headers || {};
  74. if (req.headers.origin) {
  75. headers['Access-Control-Allow-Credentials'] = 'true';
  76. headers['Access-Control-Allow-Origin'] = req.headers.origin;
  77. } else {
  78. headers['Access-Control-Allow-Origin'] = '*';
  79. }
  80. this.emit('headers', headers);
  81. return headers;
  82. };