From b7bc09db5bc165aa10ac2d771babd5e2b15f02ac Mon Sep 17 00:00:00 2001 From: Patrick Hulce Date: Mon, 16 Apr 2018 13:37:39 -0700 Subject: [PATCH] fix: handle 0-length header values and trim whitespace --- src/index.js | 2 +- test/index.js | 27 +++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 71c60a8..934c7ce 100644 --- a/src/index.js +++ b/src/index.js @@ -25,7 +25,7 @@ export default typeof fetch=='function' ? fetch.bind() : function(url, options) headers = {}, header; - request.getAllResponseHeaders().replace(/^(.*?):\s*?([\s\S]*?)$/gm, (m, key, value) => { + request.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, (m, key, value) => { keys.push(key = key.toLowerCase()); all.push([key, value]); header = headers[key]; diff --git a/test/index.js b/test/index.js index 2515ebb..fff473e 100644 --- a/test/index.js +++ b/test/index.js @@ -27,8 +27,10 @@ describe('unfetch', () => { }); describe('fetch()', () => { - it('sanity test', () => { - let xhr = { + let xhr; + + beforeEach(() => { + xhr = { setRequestHeader: spy(), getAllResponseHeaders: stub().returns('X-Foo: bar\nX-Foo:baz'), open: spy(), @@ -40,7 +42,13 @@ describe('unfetch', () => { }; global.XMLHttpRequest = stub().returns(xhr); + }); + afterEach(() => { + delete global.XMLHttpRequest; + }); + + it('sanity test', () => { let p = fetch('/foo', { headers: { a: 'b' } }) .then( r => { expect(r).to.have.property('text').that.is.a('function'); @@ -60,8 +68,6 @@ describe('unfetch', () => { expect(xhr.setRequestHeader).to.have.been.calledOnce.and.calledWith('a', 'b'); expect(xhr.open).to.have.been.calledOnce.and.calledWith('get', '/foo'); expect(xhr.send).to.have.been.calledOnce.and.calledWith(); - - delete global.XMLHttpRequest; }); expect(xhr.onload).to.be.a('function'); @@ -71,5 +77,18 @@ describe('unfetch', () => { return p; }); + + it('handles empty header values', () => { + xhr.getAllResponseHeaders = stub().returns('Server: \nX-Foo:baz'); + let p = fetch('/foo') + .then(r => { + expect(r.headers.get('server')).to.equal(''); + expect(r.headers.get('X-foo')).to.equal('baz'); + }); + + xhr.onload(); + + return p; + }); }); });