Skip to content
This repository
Browse code

res.headers, seems to work in all the browsers

  • Loading branch information...
commit f51b5e4a4d6edf4c110e429e0bea8691334888de 1 parent 105dcdb
James Halliday authored
2  example/get/main.js
@@ -3,8 +3,6 @@ var http = require('http');
3 3 http.get({ path : '/beep' }, function (res) {
4 4 var div = document.getElementById('result');
5 5
6   - div.innerHTML += JSON.stringify(res.headers) + '<br>';
7   -
8 6 res.on('data', function (buf) {
9 7 div.innerHTML += buf;
10 8 });
5 example/streaming/main.js
@@ -2,7 +2,12 @@ var http = require('http');
2 2
3 3 http.get({ path : '/doom' }, function (res) {
4 4 var div = document.getElementById('result');
  5 +
  6 + for (var key in res.headers) {
  7 + div.innerHTML += key + ' => ' + res.getHeader(key) + '<br>';
  8 + }
5 9 div.innerHTML += res.statusCode + ': ';
  10 +
6 11 if (!div.style) div.style = {};
7 12
8 13 div.style.color = 'rgb(80,80,80)';
37 lib/response.js
@@ -11,10 +11,46 @@ var capable = {
11 11 status2 : true
12 12 };
13 13
  14 +function parseHeaders (res) {
  15 + var lines = res.getAllResponseHeaders().split(/\r?\n/);
  16 + var headers = {};
  17 + for (var i = 0; i < lines.length; i++) {
  18 + var line = lines[i];
  19 + if (line === '') continue;
  20 +
  21 + var m = line.match(/^([^:]+):\s*(.*)/);
  22 + if (m) {
  23 + var key = m[1].toLowerCase(), value = m[2];
  24 +
  25 + if (headers[key] !== undefined) {
  26 + if ((Array.isArray && Array.isArray(headers[key]))
  27 + || headers[key] instanceof Array) {
  28 + headers[key].push(value);
  29 + }
  30 + else {
  31 + headers[key] = [ headers[key], value ];
  32 + }
  33 + }
  34 + else {
  35 + headers[key] = value;
  36 + }
  37 + }
  38 + else {
  39 + headers[line] = true;
  40 + }
  41 + }
  42 + return headers;
  43 +}
  44 +
  45 +Response.prototype.getHeader = function (key) {
  46 + return this.headers[key.toLowerCase()];
  47 +};
  48 +
14 49 Response.prototype.handle = function (res) {
15 50 if (res.readyState === 2 && capable.status2) {
16 51 try {
17 52 this.statusCode = res.status;
  53 + this.headers = parseHeaders(res);
18 54 }
19 55 catch (err) {
20 56 capable.status2 = false;
@@ -28,6 +64,7 @@ Response.prototype.handle = function (res) {
28 64 try {
29 65 if (!this.statusCode) {
30 66 this.statusCode = res.status;
  67 + this.headers = parseHeaders(res);
31 68 this.emit('ready');
32 69 }
33 70 }

0 comments on commit f51b5e4

Please sign in to comment.
Something went wrong with that request. Please try again.