Skip to content

Commit

Permalink
perf: request请求根据ContentType自动转换数据
Browse files Browse the repository at this point in the history
  • Loading branch information
kailong321200875 committed Jan 9, 2024
1 parent da00f8b commit ef9aa62
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/axios/index.ts
@@ -1,15 +1,21 @@
import service from './service'
import { CONTENT_TYPE } from '@/constants'
import { CONTENT_TYPE, TRANSFORM_REQUEST_DATA } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { objToFormData } from '@/utils'

const request = (option: AxiosConfig) => {
const { url, method, params, data, headers, responseType } = option
// 是否需要转换数据格式
const transformData =
TRANSFORM_REQUEST_DATA &&
(headers?.['Content-Type'] || CONTENT_TYPE) === 'multipart/form-data' &&
data
const userStore = useUserStoreWithOut()
return service.request({
url: url,
method,
params,
data,
data: transformData ? objToFormData(data) : data,
responseType: responseType,
headers: {
'Content-Type': CONTENT_TYPE,
Expand Down
11 changes: 10 additions & 1 deletion src/constants/index.ts
Expand Up @@ -6,7 +6,11 @@ export const SUCCESS_CODE = 0
/**
* 请求contentType
*/
export const CONTENT_TYPE = 'application/json'
export const CONTENT_TYPE:
| 'application/json'
| 'multipart/form-data'
| 'application/x-www-form-urlencoded'
| 'text/plain' = 'multipart/form-data'

/**
* 请求超时时间
Expand All @@ -27,3 +31,8 @@ export const NO_RESET_WHITE_LIST = ['Redirect', 'Login', 'NoFind', 'Root']
* 表格默认过滤列设置字段
*/
export const DEFAULT_FILTER_COLUMN = ['expand', 'selection']

/**
* 是否根据headers->content-type自动转换数据格式
*/
export const TRANSFORM_REQUEST_DATA = true
11 changes: 11 additions & 0 deletions src/utils/index.ts
Expand Up @@ -124,3 +124,14 @@ export function toAnyString() {
export function firstUpperCase(str: string) {
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}

/**
* 把对象转为formData
*/
export function objToFormData(obj: Recordable) {
const formData = new FormData()
Object.keys(obj).forEach((key) => {
formData.append(key, obj[key])
})
return formData
}

0 comments on commit ef9aa62

Please sign in to comment.