Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

Commit

Permalink
feat: 支持表单类型参数的序列化
Browse files Browse the repository at this point in the history
  • Loading branch information
zhbhun committed Feb 25, 2021
1 parent 59c3013 commit 2eb3eb4
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 11 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,15 @@ axios.interceptors.response.use(
}
);
```
## 兼容性
eaxios 依赖 URLSearchParams 处理表单类型的请求参数,不支持的环境需要引入响应的 polyfill
- [core-js](https://github.com/zloirock/core-js)
```js
require("core-js/modules/web.url-search-params.js")
```
- [url-search-params-polyfill](https://www.npmjs.com/package/url-search-params-polyfill)
59 changes: 48 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import axios from 'axios';
import * as Axios from 'axios';
import enhanceError from 'axios/lib/core/enhanceError';

export const EAXIOS_ERROR_CODE = {
const EAXIOS_ERROR_CODE = {
UNKNOWN: 'UNKNOWN',
REQUEST_OFFLINE: 'REQUEST_OFFLINE',
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT',
SERVER_ERROR: 'SERVER_ERROR',
Expand Down Expand Up @@ -47,6 +48,22 @@ function process(instance) {
config.transformResponse = [];
}

if (
(config.method || '').toLowerCase() === 'post' &&
(config.headers['Content-Type'] || config.headers['content-type']) ===
'application/x-www-form-urlencoded'
) {
if (config.data) {
const searchParams = new URLSearchParams('');
for (const key in config.data) {
searchParams.append(config.data[key]);
}
config.data = searchParams.toString();
} else {
config.data = '';
}
}

return config;
},
function (error) {
Expand Down Expand Up @@ -105,13 +122,19 @@ function process(instance) {
}
} catch (error) {
return Promise.reject(
enhanceError(
error,
response.config,
String(error.code || response.config.responseError.SERVER_ERROR),
response.request,
response,
),
error.isAxiosError
? error
: enhanceError(
error,
response.config,
String(
code === null || code === undefined
? EAXIOS_ERROR_CODE.UNKNOWN
: code,
),
response.request,
response,
),
);
}
},
Expand Down Expand Up @@ -145,11 +168,25 @@ function process(instance) {
const newInstance = instance.lagacyCreate(config);
return process(newInstance);
};
instance.createError = function (message, code, response) {
const error = new Error(message);
error.code = String(
code === null || code === undefined ? EAXIOS_ERROR_CODE.UNKNOWN : code,
);
if (response) {
return enhanceError(
error,
response.config,
String(error.code || response.config.responseError.UNKNOWN),
response.request,
response,
);
}
return error;
};
return instance;
}

const eaxios = process(axios);

export * from 'axios';

export default eaxios;
module.exports = eaxios;

0 comments on commit 2eb3eb4

Please sign in to comment.