From f001ebafe47ecc0ebbc74f597ac7ee904194b734 Mon Sep 17 00:00:00 2001 From: Bryan Smith Date: Mon, 25 Jan 2016 22:34:03 -0800 Subject: [PATCH] fix(http-client): ensure default content-type is respected Request's content type can be automatically set based on a body. This caused us to avoid applying a default content type. Default content types are now preferred over automatically-added content types. fixes #32 --- src/http-client.js | 4 ++++ test/http-client.spec.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/http-client.js b/src/http-client.js index bed903b..1d79e99 100644 --- a/src/http-client.js +++ b/src/http-client.js @@ -168,7 +168,11 @@ function buildRequest(input, init = {}) { let bodyObj = body ? { body } : null; let parsedDefaultHeaders = parseHeaderValues(defaults.headers); let requestInit = Object.assign({}, defaults, { headers: {} }, source, bodyObj); + let requestContentType = new Headers(requestInit.headers).get('Content-Type'); let request = new Request((this.baseUrl || '') + url, requestInit); + if (!requestContentType && new Headers(parsedDefaultHeaders).has('content-type')) { + request.headers.set('Content-Type', new Headers(parsedDefaultHeaders).get('content-type')); + } setDefaultHeaders(request.headers, parsedDefaultHeaders); if (body && Blob.prototype.isPrototypeOf(body) && body.type) { diff --git a/test/http-client.spec.js b/test/http-client.spec.js index 44eb051..9d2cbee 100644 --- a/test/http-client.spec.js +++ b/test/http-client.spec.js @@ -425,6 +425,20 @@ describe('HttpClient', () => { done(); }); }); + + it('uses default content-type header', (done) => { + fetch.and.returnValue(emptyResponse(200)); + let contentType = 'application/json;charset=UTF-8'; + client.defaults = { method: 'post', body: '{}', headers: { 'content-type': contentType } }; + + client.fetch('path') + .then(() => { + let [request] = fetch.calls.first().args; + expect(request.headers.has('content-type')).toBe(true); + expect(request.headers.get('content-type')).toBe(contentType); + done(); + }); + }); }); });