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