From f49e0e6b831fde96e5408f4072b71bb104897bd2 Mon Sep 17 00:00:00 2001 From: Alexander Fenster Date: Mon, 26 Aug 2019 15:09:45 -0700 Subject: [PATCH] fix: do not override content-type if its given (#158) * fix: do not override content-type if its given * gts fix --- src/gaxios.ts | 8 +++++++- test/test.getch.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/gaxios.ts b/src/gaxios.ts index 5541e56a..8c6bb0fd 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -187,7 +187,13 @@ export class Gaxios { opts.body = opts.data; } else if (typeof opts.data === 'object') { opts.body = JSON.stringify(opts.data); - opts.headers['Content-Type'] = 'application/json'; + if ( + !Object.keys(opts.headers).some((key: string) => + key.match(/^content-type$/i) + ) + ) { + opts.headers['Content-Type'] = 'application/json'; + } } else { opts.body = opts.data; } diff --git a/test/test.getch.ts b/test/test.getch.ts index ddcaf583..da47708d 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -292,6 +292,37 @@ describe('🎏 data handling', () => { assert.deepStrictEqual(res.data, {}); }); + it('should set content-type for object request', async () => { + const body = {hello: '🌎'}; + const scope = nock(url) + .matchHeader('content-type', 'application/json') + .post('/', JSON.stringify(body)) + .reply(200, {}); + const res = await request({ + url, + method: 'POST', + data: body, + }); + scope.done(); + assert.deepStrictEqual(res.data, {}); + }); + + it('should allow to override content-type for object request', async () => { + const body = {hello: '🌎'}; + const scope = nock(url) + .matchHeader('content-type', 'application/octet-stream') + .post('/', JSON.stringify(body)) + .reply(200, {}); + const res = await request({ + url, + method: 'POST', + data: body, + headers: {'content-type': 'application/octet-stream'}, + }); + scope.done(); + assert.deepStrictEqual(res.data, {}); + }); + it('should return stream if asked nicely', async () => { const body = {hello: '🌎'}; const scope = nock(url)