polling-xhr.js (1239B)
1 2 /** 3 * Module dependencies. 4 */ 5 6 var Polling = require('./polling'); 7 var util = require('util'); 8 9 /** 10 * Module exports. 11 */ 12 13 module.exports = XHR; 14 15 /** 16 * Ajax polling transport. 17 * 18 * @api public 19 */ 20 21 function XHR (req) { 22 Polling.call(this, req); 23 } 24 25 /** 26 * Inherits from Polling. 27 */ 28 29 util.inherits(XHR, Polling); 30 31 /** 32 * Overrides `onRequest` to handle `OPTIONS`.. 33 * 34 * @param {http.IncomingMessage} 35 * @api private 36 */ 37 38 XHR.prototype.onRequest = function (req) { 39 if ('OPTIONS' === req.method) { 40 var res = req.res; 41 var headers = this.headers(req); 42 headers['Access-Control-Allow-Headers'] = 'Content-Type'; 43 res.writeHead(200, headers); 44 res.end(); 45 } else { 46 Polling.prototype.onRequest.call(this, req); 47 } 48 }; 49 50 /** 51 * Returns headers for a response. 52 * 53 * @param {http.IncomingMessage} request 54 * @param {Object} extra headers 55 * @api private 56 */ 57 58 XHR.prototype.headers = function (req, headers) { 59 headers = headers || {}; 60 61 if (req.headers.origin) { 62 headers['Access-Control-Allow-Credentials'] = 'true'; 63 headers['Access-Control-Allow-Origin'] = req.headers.origin; 64 } else { 65 headers['Access-Control-Allow-Origin'] = '*'; 66 } 67 68 return Polling.prototype.headers.call(this, req, headers); 69 };