Skip to content

Commit a83712a

Browse files
authored
feat(axios): use JSON.stringify and set content-type for post requests (#46)
* feat(axios): use JSON.stringify and set content-type for post requests * perf: add charset=utf-8
1 parent 1f379af commit a83712a

File tree

8 files changed

+68
-6
lines changed

8 files changed

+68
-6
lines changed

docs/config/common.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ export default {
117117
::: tip
118118
* 如果想要发送二进制数据可以参阅 [FormData](../guide/form-data.md#formdata) 章节
119119
* 如果请求头上的一些数据是异步获取到的,比如小程序端的 `cookie`。建议配置下面的 `beforeFn` 函数或是中间件,异步设置请求头。
120+
* <badge text="1.5.0+" /> 若当前以 `post` 的方式发送请求,且当前没有配置 `transformRequest` 时,`tua-api` 会自动调用 `JSON.stringify`,并设置 `Content-Type``'application/json'`
120121
:::
121122

122123
## beforeFn 发起请求前钩子函数

examples/apis-web/fake-post.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,5 +71,22 @@ export default {
7171
// 表示这个接口不需要传递 commonParams
7272
commonParams: null,
7373
},
74+
/**
75+
* custom-transformRequest
76+
*/
77+
{
78+
name: 'ct',
79+
path: 'custom-transformRequest',
80+
axiosOptions: {
81+
transformRequest: () => `ct`,
82+
},
83+
},
84+
/**
85+
* application/json
86+
*/
87+
{
88+
name: 'pj',
89+
path: 'post-json',
90+
},
7491
],
7592
}

examples/apis-web/index.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ export const fakeGetApi: {
4040
}
4141

4242
export const fakePostApi: {
43+
'ct': ReqFnWithAnyParams
4344
'oh': ReqFnWithAnyParams
45+
'pj': ReqFnWithAnyParams
4446
'eap': ReqFnWithAnyParams
4547
'hap': ReqFnWithAnyParams
4648
'ap': ReqFn & {

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "tua-api",
3-
"version": "1.4.4",
3+
"version": "1.5.0",
44
"description": "🏗 A common tool helps converting configs to api functions",
55
"main": "dist/TuaApi.cjs.js",
66
"module": "dist/TuaApi.esm.js",

src/adapters/axios.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import axios from 'axios'
22

33
import { DEFAULT_HEADER } from '../constants'
4-
import { logger, isFormData, getParamStrFromObj } from '../utils'
4+
import { logger, isFormData, isUndefined, getParamStrFromObj } from '../utils'
55

66
/**
77
* 获取使用 axios 发起请求后的 promise 对象
@@ -11,20 +11,34 @@ export const getAxiosPromise = ({
1111
url,
1212
data,
1313
method,
14-
headers = DEFAULT_HEADER,
14+
headers,
1515
crossDomain = true,
1616
withCredentials = true,
17-
transformRequest = [getParamStrFromObj],
17+
transformRequest,
1818
...rest
1919
}) => {
2020
const isFD = isFormData(data)
21+
const isPost = method.toLowerCase() === 'post'
2122

2223
logger.log(`Req Url: ${url}`)
2324
if (data && (Object.keys(data).length || isFD)) {
2425
logger.log('Req Data:', data)
2526
}
2627

27-
transformRequest = isFD ? null : transformRequest
28+
// 优先使用用户的配置
29+
if (isUndefined(transformRequest)) {
30+
transformRequest = isFD
31+
? null
32+
: isPost
33+
// 如果使用 post 的请求方式,自动对其 stringify
34+
? x => JSON.stringify(x)
35+
: getParamStrFromObj
36+
}
37+
if (isUndefined(headers)) {
38+
headers = isPost
39+
? { 'Content-Type': 'application/json;charset=utf-8' }
40+
: DEFAULT_HEADER
41+
}
2842

2943
return axios({
3044
url,

src/constants.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const VALID_REQ_TYPES = ['wx', 'axios', 'jsonp']
55
const WX_VALID_METHODS = ['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']
66

77
// 默认请求头
8-
const DEFAULT_HEADER = { 'Content-Type': 'application/x-www-form-urlencoded' }
8+
const DEFAULT_HEADER = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }
99

1010
// 错误信息
1111
const ERROR_STRINGS = {

src/utils/judge.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,5 @@ export const isFormData = (val) => (
77
(typeof FormData !== 'undefined') &&
88
(val instanceof FormData)
99
)
10+
11+
export const isUndefined = val => typeof val === 'undefined'

test/__tests__/axios.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import axios from 'axios'
22
import MockAdapter from 'axios-mock-adapter'
33

4+
import fakePostConfig from '@examples/apis-web/fake-post'
45
import { ERROR_STRINGS } from '@/constants'
56
import { fakeGetApi, fakePostApi } from '@examples/apis-web/'
67

@@ -19,6 +20,8 @@ const reqTAUrl = 'http://example-base.com/fake-get/req-type-axios?asyncCp=asyncC
1920
const reqEAPUrl = 'http://example-base.com/fake-post/empty-array-params'
2021
const reqMFDUrl = 'http://example-base.com/fake-get/mock-function-data'
2122
const reqBFCUrl = 'http://example-base.com/fake-get/beforeFn-cookie'
23+
const reqCTUrl = 'http://example-base.com/fake-post/custom-transformRequest'
24+
const reqPjUrl = 'http://example-base.com/fake-post/post-json'
2225

2326
describe('middleware', () => {
2427
test('change baseUrl before request', async () => {
@@ -164,4 +167,27 @@ describe('fake post requests', () => {
164167
expect(data).toBe(formData)
165168
expect(transformRequest).toBe(null)
166169
})
170+
171+
test('custom-transformRequest', async () => {
172+
mock.resetHistory()
173+
mock.onPost(reqCTUrl).reply(200, {})
174+
175+
await fakePostApi.ct()
176+
177+
const { data } = mock.history.post[0]
178+
179+
expect(data).toBe('ct')
180+
})
181+
182+
test('post-json', async () => {
183+
mock.resetHistory()
184+
mock.onPost(reqPjUrl).reply(200, {})
185+
186+
await fakePostApi.pj()
187+
188+
const { data } = mock.history.post[0]
189+
190+
expect(data).toBe(JSON.stringify(fakePostConfig.commonParams))
191+
expect(mock.history.post[0].headers['Content-Type']).toBe('application/json;charset=utf-8')
192+
})
167193
})

0 commit comments

Comments
 (0)