From 89e0ef0c368ee3f02cea5ea5a87ff284bdcdfb9f Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Fri, 9 Oct 2020 19:43:52 +0800 Subject: [PATCH] fix(h5): unify the default content-type (#7796) * fix(h5): unify the default content-type * fix(style): remove trailing spaces * fix(h5): improve the solution * fix(h5): update test case Co-authored-by: Yue, Zongkun --- packages/taro-h5/__test__/request-test.js | 7 +++---- packages/taro-h5/src/api/request/index.js | 9 ++++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/taro-h5/__test__/request-test.js b/packages/taro-h5/__test__/request-test.js index 46e1bbf3b0bb..1a77552f9223 100644 --- a/packages/taro-h5/__test__/request-test.js +++ b/packages/taro-h5/__test__/request-test.js @@ -73,11 +73,10 @@ describe('request', () => { expect(fetch.mock.calls[0][0]).toBe('https://github.com') expect(fetch.mock.calls[0][1]).toEqual({ method: 'POST', - body: { - arg: 123 - }, + body: JSON.stringify({ arg: 123 }), headers: { - 'A': 'CCC' + 'A': 'CCC', + 'Content-Type': 'application/json' }, mode: 'cors', cache: 'no-cache', diff --git a/packages/taro-h5/src/api/request/index.js b/packages/taro-h5/src/api/request/index.js index eb11ccb1e1e6..f67a79bce87c 100644 --- a/packages/taro-h5/src/api/request/index.js +++ b/packages/taro-h5/src/api/request/index.js @@ -52,10 +52,13 @@ function _request (options) { if (methodUpper === 'GET' || methodUpper === 'HEAD') { url = generateRequestUrlWithParams(url, options.data) } else if (typeof options.data === 'object') { - const contentType = options.header && (options.header['Content-Type'] || options.header['content-type']) - if (contentType && contentType.indexOf('application/json') >= 0) { + options.header = options.header || {} + options.header['Content-Type'] = options.header['Content-Type'] || options.header['content-type'] || 'application/json' + const contentType = options.header['Content-Type'] + + if (contentType.indexOf('application/json') >= 0) { params.body = JSON.stringify(options.data) - } else if (contentType && contentType.indexOf('application/x-www-form-urlencoded') >= 0) { + } else if (contentType.indexOf('application/x-www-form-urlencoded') >= 0) { params.body = serializeParams(options.data) } else { params.body = options.data