test-headers.js (2584B)
1 var sys = require("util") 2 , assert = require("assert") 3 , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest 4 , xhr = new XMLHttpRequest() 5 , http = require("http"); 6 7 // Test server 8 var server = http.createServer(function (req, res) { 9 // Test setRequestHeader 10 assert.equal("Foobar", req.headers["x-test"]); 11 // Test non-conforming allowed header 12 assert.equal("node-XMLHttpRequest-test", req.headers["user-agent"]); 13 // Test header set with blacklist disabled 14 assert.equal("http://github.com", req.headers["referer"]); 15 16 var body = "Hello World"; 17 res.writeHead(200, { 18 "Content-Type": "text/plain", 19 "Content-Length": Buffer.byteLength(body), 20 // Set cookie headers to see if they're correctly suppressed 21 // Actual values don't matter 22 "Set-Cookie": "foo=bar", 23 "Set-Cookie2": "bar=baz", 24 "Date": "Thu, 30 Aug 2012 18:17:53 GMT", 25 "Connection": "close" 26 }); 27 res.write("Hello World"); 28 res.end(); 29 30 this.close(); 31 }).listen(8000); 32 33 xhr.onreadystatechange = function() { 34 if (this.readyState == 4) { 35 // Test getAllResponseHeaders() 36 var headers = "content-type: text/plain\r\ncontent-length: 11\r\ndate: Thu, 30 Aug 2012 18:17:53 GMT\r\nconnection: close"; 37 assert.equal(headers, this.getAllResponseHeaders()); 38 39 // Test case insensitivity 40 assert.equal('text/plain', this.getResponseHeader('Content-Type')); 41 assert.equal('text/plain', this.getResponseHeader('Content-type')); 42 assert.equal('text/plain', this.getResponseHeader('content-Type')); 43 assert.equal('text/plain', this.getResponseHeader('content-type')); 44 45 // Test aborted getAllResponseHeaders 46 this.abort(); 47 assert.equal("", this.getAllResponseHeaders()); 48 assert.equal(null, this.getResponseHeader("Connection")); 49 50 sys.puts("done"); 51 } 52 }; 53 54 assert.equal(null, xhr.getResponseHeader("Content-Type")); 55 try { 56 xhr.open("GET", "http://localhost:8000/"); 57 // Valid header 58 xhr.setRequestHeader("X-Test", "Foobar"); 59 // Invalid header 60 xhr.setRequestHeader("Content-Length", 0); 61 // Allowed header outside of specs 62 xhr.setRequestHeader("user-agent", "node-XMLHttpRequest-test"); 63 // Test getRequestHeader 64 assert.equal("Foobar", xhr.getRequestHeader("X-Test")); 65 // Test invalid header 66 assert.equal("", xhr.getRequestHeader("Content-Length")); 67 68 // Test allowing all headers 69 xhr.setDisableHeaderCheck(true); 70 xhr.setRequestHeader("Referer", "http://github.com"); 71 assert.equal("http://github.com", xhr.getRequestHeader("Referer")); 72 73 xhr.send(); 74 } catch(e) { 75 console.log("ERROR: Exception raised", e); 76 }