Compare commits

...

30 Commits
v2.4.1 ... main

Author SHA1 Message Date
zjx0905 9c9debbc17 chore: release v2.7.2 2024-01-31 19:15:27 +08:00
zjxxxxxxxxx c0352a5d6a
docs: 修复安装方式错误 (#58)
#57
2024-01-25 19:12:17 +08:00
zjxxxxxxxxx 5d45cd9670
fix: 修复设置请求 headers 影响了全局配置 (#56)
#55
2024-01-10 19:33:33 +08:00
zjx0905 6af2d8e5c3 chore: release v2.7.1 2023-12-16 12:48:10 +08:00
zjxxxxxxxxx df42674895
fix: 对上传文件响应数据JSON.parse (#54)
#53
2023-12-14 10:43:17 +08:00
zjxxxxxxxxx 3848fdd81b
feat: 添加符合 HTTP 规范的 statusText (#49) 2023-11-01 07:45:19 -05:00
zjx0905 7e7330405e chore: update format 2023-09-22 15:34:49 +08:00
zjx0905 5eaecd8b55 chore: 示例配置 allowedHosts 2023-08-17 17:11:57 +08:00
zjx0905 0c9fb2034a chore: 示例锁定 3000 端口号 2023-08-17 17:04:27 +08:00
zjx0905 2bc03961ce chore: release v2.7.0 2023-08-17 14:06:20 +08:00
zjx0905 4f91a45293 chore: 配置 CodeSandbox 和 Stackblitz 2023-08-17 13:41:55 +08:00
zjx0905 53f043275c feat: 新增支持小红书小程序 2023-08-15 15:43:24 +08:00
zjx0905 71e3007389 fix: 修复 errno 和 errMsg 丢失 2023-08-13 14:04:06 +08:00
zjx0905 391b47d7a9 docs: 升级 pnpm 2023-08-13 10:26:42 +08:00
zjx0905 6498923e9a chore: release v2.6.0 2023-08-13 10:22:29 +08:00
zjx0905 c57a01fd9e ci: 更新 pnpm 版本 2023-08-12 22:31:19 +08:00
zjx0905 a04f833d91 feat: 废弃 fork API
BREAKING CHANGE :
axios.fork() 已废弃
2023-08-12 22:08:44 +08:00
zjx0905 158d26fa64 chore: 更新所有者信息 2023-08-12 15:48:36 +08:00
zjx0905 11f69630a4 chore: release v2.5.0 2023-06-04 19:48:32 +08:00
zjx0905 96ea0266dd feat: 移除内置的 uni 适配器
BREAKING CHANGE :
uni 不再内部支持, 可以参阅文档中的自定义适配器自行适配 uni

#40
2023-06-04 19:44:32 +08:00
zjx0905 2496333e42 chore: release v2.4.2 2023-05-14 21:45:16 +08:00
zjx0905 3f4a8a12e0 chore: 隐藏内部使用类型 2023-05-14 21:44:08 +08:00
zjx0905 a1281f86a5 chore: 类型检查 2023-05-14 20:55:47 +08:00
zjx0905 7c60b723e1 chore: 修改 scripts 2023-05-14 19:12:47 +08:00
zjx0905 17022d2c98 chore: 编写基础示例 2023-05-09 20:35:31 +08:00
zjx0905 b6698ca22d feat: 发出请求前进行动态地址插值 2023-05-09 20:34:50 +08:00
zjx0905 6f1093fe1c docs: 移除边框 2023-05-08 15:57:18 +08:00
zjx0905 1152853ce2 docs: 修正下载文件示例 2023-05-07 23:16:28 +08:00
zjx0905 359b09172e docs: 初始化示例项目 2023-05-05 10:59:37 +08:00
zjx0905 74856f7fde fix: axios.use 函数返回值不是当前实例 2023-05-04 16:26:59 +08:00
106 changed files with 17718 additions and 3310 deletions

View File

@ -1 +1,4 @@
/dist
dist/
example/dist/
example/config/**.js

View File

@ -1,15 +1,16 @@
{
"env": {
"es2022": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"root": true,
"rules": {
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/ban-ts-comment": 0
}
"root": true,
"env": {
"es2022": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/ban-ts-comment": 0,
"no-mixed-spaces-and-tabs": 0
}
}

View File

@ -37,13 +37,13 @@ body:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md).
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjx0905/axios-miniprogram/issues)以避免创建重复。
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)以避免创建重复。
required: true
- label: 确保这是 axios-miniprogram 问题而不是特定于框架的问题。
required: true

View File

@ -17,7 +17,7 @@ body:
id: suggested-solution
attributes:
label: 建议的解决方案
description: '在模块 [xy] 中,我们可以提供以下实现......'
description: '我们可以提供以下实现......'
validations:
required: true
- type: textarea
@ -36,9 +36,9 @@ body:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md).
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true

View File

@ -24,7 +24,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -33,7 +33,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Lint
run: pnpm lint

View File

@ -18,7 +18,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -27,7 +27,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Build
run: pnpm docs:build

View File

@ -15,7 +15,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -24,7 +24,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Build
run: pnpm build -a

View File

@ -15,7 +15,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -24,7 +24,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Build Release Assets
run: pnpm build:assets
@ -44,7 +44,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
name: Release ${{ github.ref }}
name: Release ${{ github.ref_name }}
prerelease: ${{ steps.prerelease.outputs.result }}
body_path: 'RELEASELOG.md'
files: 'dist/**.zip'

4
.gitignore vendored
View File

@ -3,7 +3,6 @@ node_modules
*.log
# Docs
dist
docs/.vitepress/cache
docs/pages/guide/intro.md
@ -11,7 +10,8 @@ docs/pages/guide/intro.md
.DS_Store
# Bundle
lib/
dist/
.swc
# Typescript build file
*.tsbuildinfo

View File

@ -1 +1,5 @@
CHANGELOG.md
dist/
example/dist/
example/config/**.js

View File

@ -1,11 +1,10 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": true,
"semi": false,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"jsxSingleQuote": true
"arrowParens": "always"
}

View File

@ -1,44 +1,123 @@
## [2.4.1](https://github.com/zjx0905/axios-miniprogram/compare/v2.4.0...v2.4.1) (2023-05-04)
## [2.7.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.7.1...v2.7.2) (2024-01-31)
### Bug Fixes
* 配置原始 URL 丢失 ([8b6eed2](https://github.com/zjx0905/axios-miniprogram/commit/8b6eed2d6df5c7aacd181f6fbcfba9eca875178c))
* 配置原始请求方法丢失 ([c107171](https://github.com/zjx0905/axios-miniprogram/commit/c107171eba69a129eddad34861611837a0efac25))
* 修复设置请求 headers 影响了全局配置 ([#56](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/56)) ([5d45cd9](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/5d45cd9670c3bc8b58437d2defc58753ebc6392e)), closes [#55](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/55)
## [2.7.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.7.0...v2.7.1) (2023-12-16)
### Bug Fixes
* 对上传文件响应数据JSON.parse ([#54](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/54)) ([df42674](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/df4267489508f6d1851f52d78e9d9179709a562a)), closes [#53](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/53)
### Features
* 请求发送前请求方法转小写 ([0b82403](https://github.com/zjx0905/axios-miniprogram/commit/0b82403c4c630676042ff390b77d5791c4ab0a6e))
* 允许设置默认请求方法 ([4b02582](https://github.com/zjx0905/axios-miniprogram/commit/4b025821525712d7e6bb68faa9af3cf7d9ad0e0d))
* getUri 支持 baseURL/dynamicURL ([633c920](https://github.com/zjx0905/axios-miniprogram/commit/633c92024718370e24919fcfb44b86b795248c8f))
* 添加符合 HTTP 规范的 statusText ([#49](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/49)) ([3848fdd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/3848fdd81bf8fb1f5e373ca4e117adb653969acf))
# [2.7.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.6.0...v2.7.0) (2023-08-17)
### Bug Fixes
* 修复 errno 和 errMsg 丢失 ([71e3007](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/71e30073890974f54461134620dfbda58cc36af0))
### Features
* 新增支持小红书小程序 ([53f0432](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/53f043275ced79c7204d791c62721e36db512f24))
# [2.6.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.5.0...v2.6.0) (2023-08-13)
### Features
* 废弃 fork API ([a04f833](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/a04f833d917cb07c3bd95678260971194179def0))
### BREAKING CHANGES
* axios.fork() 已废弃
# [2.5.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.2...v2.5.0) (2023-06-04)
### Features
* 移除内置的 uni 适配器 ([96ea026](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/96ea0266dd7c0da26341d8fea4d3bdb53361ffd0)), closes [#40](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/40)
### BREAKING CHANGES
* uni 不再内部支持, 可以参阅文档中的自定义适配器自行适配 uni
## [2.4.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.1...v2.4.2) (2023-05-14)
### Bug Fixes
* axios.use 函数返回值不是当前实例 ([74856f7](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/74856f7fdef4f0e75b8665300960416a840f561c))
### Features
* 发出请求前进行动态地址插值 ([b6698ca](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b6698ca22da3f754e21916e69d43b961e12571e6))
## [2.4.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.0...v2.4.1) (2023-05-04)
### Bug Fixes
* 配置原始 URL 丢失 ([8b6eed2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/8b6eed2d6df5c7aacd181f6fbcfba9eca875178c))
* 配置原始请求方法丢失 ([c107171](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/c107171eba69a129eddad34861611837a0efac25))
### Features
* 请求发送前请求方法转小写 ([0b82403](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0b82403c4c630676042ff390b77d5791c4ab0a6e))
* 允许设置默认请求方法 ([4b02582](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4b025821525712d7e6bb68faa9af3cf7d9ad0e0d))
* getUri 支持 baseURL/dynamicURL ([633c920](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/633c92024718370e24919fcfb44b86b795248c8f))
### Performance Improvements
* 优化中间件 ([3931f23](https://github.com/zjx0905/axios-miniprogram/commit/3931f230deffbb72a70fd24798334e63a3d531f9))
* 优化中间件 ([3931f23](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/3931f230deffbb72a70fd24798334e63a3d531f9))
# [2.4.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.3.2...v2.4.0) (2023-04-25)
# [2.4.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.2...v2.4.0) (2023-04-25)
### Bug Fixes
* 丢失末尾自带的斜线 ([db787a2](https://github.com/zjx0905/axios-miniprogram/commit/db787a2b5f7f1188d1813ddb715ef23e653120a9)), closes [#44](https://github.com/zjx0905/axios-miniprogram/issues/44)
* 丢失末尾自带的斜线 ([db787a2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/db787a2b5f7f1188d1813ddb715ef23e653120a9)), closes [#44](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/44)
### Features
* 全局方法 create 改为实例方法 ([a84533a](https://github.com/zjx0905/axios-miniprogram/commit/a84533a09f493e27ba3e567549be5e534271ed22))
* 添加扩展实例 ([9093e1b](https://github.com/zjx0905/axios-miniprogram/commit/9093e1bdffe5bd75fccfeeeeb0e2b487751c549a))
* 添加中间件 ([6263759](https://github.com/zjx0905/axios-miniprogram/commit/6263759ba94b2269082c49a2f2a5e038f6766027))
* 支持复用父级中间件 ([bfc012b](https://github.com/zjx0905/axios-miniprogram/commit/bfc012b4999d717629b997ab908fd411954b0323))
* 全局方法 create 改为实例方法 ([a84533a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/a84533a09f493e27ba3e567549be5e534271ed22))
* 添加扩展实例 ([9093e1b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/9093e1bdffe5bd75fccfeeeeb0e2b487751c549a))
* 添加中间件 ([6263759](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/6263759ba94b2269082c49a2f2a5e038f6766027))
* 支持复用父级中间件 ([bfc012b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/bfc012b4999d717629b997ab908fd411954b0323))
### Reverts
* 取消支持为路径添加中间件 ([1e5809a](https://github.com/zjx0905/axios-miniprogram/commit/1e5809aee3f1653eced0c2ca351c6e3f8616f719))
* 取消支持为路径添加中间件 ([1e5809a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1e5809aee3f1653eced0c2ca351c6e3f8616f719))
### BREAKING CHANGES
@ -47,94 +126,94 @@
## [2.3.2](https://github.com/zjx0905/axios-miniprogram/compare/v2.3.1...v2.3.2) (2023-04-23)
## [2.3.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.1...v2.3.2) (2023-04-23)
### Bug Fixes
* 适配器请求头丢失 ([c0ca900](https://github.com/zjx0905/axios-miniprogram/commit/c0ca9001d2dc2b138a916c18da000b733d58ec7a)), closes [#43](https://github.com/zjx0905/axios-miniprogram/issues/43)
* 适配器请求头丢失 ([c0ca900](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/c0ca9001d2dc2b138a916c18da000b733d58ec7a)), closes [#43](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/43)
## [2.3.1](https://github.com/zjx0905/axios-miniprogram/compare/v2.3.0...v2.3.1) (2023-04-21)
## [2.3.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.0...v2.3.1) (2023-04-21)
### Bug Fixes
* 控制台没有输出适配器错误 ([258954a](https://github.com/zjx0905/axios-miniprogram/commit/258954afc1c39483ff6b1828c8904c5b284890d2))
* 下载进度/上传进度 类型错误 ([2d691b6](https://github.com/zjx0905/axios-miniprogram/commit/2d691b69cbb2d3e27be3698bf4a4188cf71ccb7e))
* 控制台没有输出适配器错误 ([258954a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/258954afc1c39483ff6b1828c8904c5b284890d2))
* 下载进度/上传进度 类型错误 ([2d691b6](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2d691b69cbb2d3e27be3698bf4a4188cf71ccb7e))
### Features
* 添加版本号 ([e3346a8](https://github.com/zjx0905/axios-miniprogram/commit/e3346a866f12ed8aa07695f45a8177d631973abd))
* 添加版本号 ([e3346a8](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/e3346a866f12ed8aa07695f45a8177d631973abd))
# [2.3.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.2.0...v2.3.0) (2023-04-18)
# [2.3.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.2.0...v2.3.0) (2023-04-18)
### Bug Fixes
* 错误处理不是每次出错都执行 ([fb4762d](https://github.com/zjx0905/axios-miniprogram/commit/fb4762d01a0d304ce6c291d6487dce1507a985c5))
* data 不支持对象以外的类型 ([4d8ec80](https://github.com/zjx0905/axios-miniprogram/commit/4d8ec80f29b85e3419d1bc5112886a397ee2cc48))
* 错误处理不是每次出错都执行 ([fb4762d](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/fb4762d01a0d304ce6c291d6487dce1507a985c5))
* data 不支持对象以外的类型 ([4d8ec80](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4d8ec80f29b85e3419d1bc5112886a397ee2cc48))
### Features
* 从参数中删除动态地址属性 ([b0eaa04](https://github.com/zjx0905/axios-miniprogram/commit/b0eaa04c66dc82de944769893f62ecd0c4ae76d8))
* 提供更多可使用的类型 ([0dc58a4](https://github.com/zjx0905/axios-miniprogram/commit/0dc58a4b0cdd5d36c1b16f13697d8180952cb093))
* 支持具名导入工具函数 ([d714ed2](https://github.com/zjx0905/axios-miniprogram/commit/d714ed23c0f3b8ea3abecfb042c67bcf9adb29a7))
* 支持清空拦截器 ([cbcc43a](https://github.com/zjx0905/axios-miniprogram/commit/cbcc43ad77f0e79223e524aa6bb4502ee4b989c9))
* 从参数中删除动态地址属性 ([b0eaa04](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b0eaa04c66dc82de944769893f62ecd0c4ae76d8))
* 提供更多可使用的类型 ([0dc58a4](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0dc58a4b0cdd5d36c1b16f13697d8180952cb093))
* 支持具名导入工具函数 ([d714ed2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/d714ed23c0f3b8ea3abecfb042c67bcf9adb29a7))
* 支持清空拦截器 ([cbcc43a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/cbcc43ad77f0e79223e524aa6bb4502ee4b989c9))
# [2.2.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.1.0...v2.2.0) (2023-04-16)
# [2.2.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.1.0...v2.2.0) (2023-04-16)
### Bug Fixes
* 修复 Proxy uni 错误 ([021e052](https://github.com/zjx0905/axios-miniprogram/commit/021e05233a95ebc5c5f93d114d225cc45a22675f))
* 修复 Proxy uni 错误 ([021e052](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/021e05233a95ebc5c5f93d114d225cc45a22675f))
### Features
* 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjx0905/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77))
* 支持 HTTP PATCH 请求 ([22bcefc](https://github.com/zjx0905/axios-miniprogram/commit/22bcefcb97e50400403b131d307c97eb4cbb6071))
* 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77))
* 支持 HTTP PATCH 请求 ([22bcefc](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/22bcefcb97e50400403b131d307c97eb4cbb6071))
# [2.1.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0...v2.1.0) (2023-04-11)
# [2.1.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0...v2.1.0) (2023-04-11)
### Bug Fixes
* 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjx0905/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136))
* 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjx0905/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8))
* 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136))
* 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8))
### Features
* 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjx0905/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777))
* 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjx0905/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9))
* 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjx0905/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7))
* 支持深度合并 params & data ([22f65cf](https://github.com/zjx0905/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f))
* fileName 替换为 name ([69044f3](https://github.com/zjx0905/axios-miniprogram/commit/69044f35833d8d42a5f0c12b01687298c08f589b))
* 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777))
* 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9))
* 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7))
* 支持深度合并 params & data ([22f65cf](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f))
* fileName 替换为 name ([69044f3](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/69044f35833d8d42a5f0c12b01687298c08f589b))
# [2.0.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0-beta.10...v2.0.0) (2023-04-05)
# [2.0.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0-beta.10...v2.0.0) (2023-04-05)
### Bug Fixes
* 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjx0905/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a))
* 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a))
### Features
* 添加新的 API isAxiosError ([61337a9](https://github.com/zjx0905/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842))
* 优化 defaults ([2793dd8](https://github.com/zjx0905/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf))
* 添加新的 API isAxiosError ([61337a9](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842))
* 优化 defaults ([2793dd8](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf))
### BREAKING CHANGES
@ -143,12 +222,12 @@
# [2.0.0-beta.10](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0-beta.0...v2.0.0-beta.10) (2023-04-05)
# [2.0.0-beta.10](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0-beta.0...v2.0.0-beta.10) (2023-04-05)
### Features
* 支持 es2015 ([b66176f](https://github.com/zjx0905/axios-miniprogram/commit/b66176f0ed90eaec5c1377077359a234691ae1b3))
* 支持 es2015 ([b66176f](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b66176f0ed90eaec5c1377077359a234691ae1b3))
@ -156,14 +235,14 @@
### Bug Fixes
* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjx0905/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))
* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))
### Features
* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjx0905/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjx0905/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjx0905/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjx0905/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjx0905/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))
* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))
### BREAKING CHANGES

View File

@ -34,7 +34,7 @@ pnpm cz
脚本列表
- `pnpm build` 打包源代码
- `pnpm watch` 监听文件变更并运行 `build`
- `pnpm dev` 监听文件变更并运行 `build`
- `pnpm test` 单元测试
- `pnpm test:watch` 监听文件变更并运行 `test`
- `pnpm test:cov` 运行 `test` 并输出测试覆盖率
@ -50,7 +50,7 @@ pnpm cz
添加新功能有一些注意事项。
- 在你开始工作之前,最好先开一个 [issue](https://github.com/zjx0905/axios-miniprogram/issues) 来讨论。
- 在你开始工作之前,最好先开一个 [issue](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 来讨论。
- 应该对新功能进行单元测试。
- 应该在文档中添加相关的使用介绍及方法。

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2020-present, zjx0905 <https://github.com/zjx0905>
Copyright (c) 2020-present, zjxxxxxxxxx <https://github.com/zjxxxxxxxxx>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,24 +1,26 @@
# axios-miniprogram
<h1 align="center">axios-miniprogram</h1>
<p style="display: flex;margin-left:-5px;">
<a href="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci">
<p style="text-align: center;" align="center">
<a style="display: inline-block;margin-left: 5px;" href="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci"/>
</a>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/npm/v/axios-miniprogram" alt="npm">
<a style="display: inline-block;margin-left: 5px;" href="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram" >
<img src="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
</a>
<a style="margin-left:5px;" href="https://codecov.io/gh/zjx0905/axios-miniprogram" >
<img src="https://codecov.io/gh/zjx0905/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
<a style="display: inline-block;margin-left: 5px;" href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/zjxxxxxxxxx/axios-miniprogram" alt="license"/>
</a>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size">
<a style="display: inline-block;margin-left: 5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size"/>
</a>
<a style="margin-left:5px;" href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/zjx0905/axios-miniprogram" alt="license">
<a style="display: inline-block;" href="https://www.npmjs.org/package/axios-miniprogram">
<img alt="npm" src="https://img.shields.io/npm/dt/axios-miniprogram"/>
</a>
</p>
[中文文档](https://axios-miniprogram.com)
<p style="text-align: center;" align="center">
<a href='https://axios-miniprogram.com'>中文文档</a>
</p>
## axios-miniprogram 是什么?
@ -51,17 +53,28 @@ axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库
- [飞书小程序](https://open.feishu.cn/document/uYjL24iN/uMjNzUjLzYzM14yM2MTN?from=axios-miniprogram)
- [快手小程序](https://mp.kuaishou.com/docs/introduction/quickStart.html?from=axios-miniprogram)
- [360 小程序](https://mp.360.cn/doc/miniprogram/dev/#/f4b41f0cc5683bce78dfadfa7f3c73e7?from=axios-miniprogram)
- [小红书小程序](https://miniapp.xiaohongshu.com/docs/guide/miniIntroduce?from=axios-miniprogram)
## 关于在跨端框架中使用时的支持度
问:在 uni-app 或者 Taro 等等这类跨端框架中使用时,该请求库支持 h5APPvue3react 等等吗?
问:在 uni-app 或者 Taro 等等这类跨端框架中使用时,该请求库支持 h5APPvue3 等等吗?
答:该请求库只是对框架提供的请求 API 进行了封装,并没有使用什么黑魔法。理论上来讲,框架支持的平台,该库也必然支持。
有问题欢迎反馈,请尽量把问题提到 [github issues](https://github.com/zjx0905/axios-miniprogram/issues) 中,这样更容易被我注意到。
有问题欢迎反馈,请尽量把问题提到 [github issues](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 中,这样更容易被我注意到。
[提问点这里](https://github.com/zjx0905/axios-miniprogram/issues)
[提问点这里](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)
## 未来计划
## 跨端框架示例
2023 年 6 月 1 日 起该库将不再内部支持第三方框架,内置的 uni-app 即将移除,您依旧可以使用[适配器](https://axios-miniprogram.com/advanced/adapter)兼容 uni-app。
### Taro
- [源代码](https://github.com/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
- [CodeSandbox](https://codesandbox.io/p/sandbox/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
- [StackBlitz](https://stackblitz.com/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
### uni-app
- [源代码](https://github.com/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)
- [CodeSandbox](https://codesandbox.io/p/sandbox/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)
- [StackBlitz](https://stackblitz.com/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)

View File

@ -21,7 +21,7 @@ export default defineConfig({
{ text: '入门', link: '/basics/request', activeMatch: '/basics/' },
{
text: '进阶',
link: '/advanced/request-interceptor',
link: '/advanced/middleware',
activeMatch: '/advanced/',
},
],
@ -29,15 +29,18 @@ export default defineConfig({
sidebar: sidebar(),
socialLinks: [
{ icon: 'github', link: 'https://github.com/zjx0905/axios-miniprogram' },
{
icon: 'github',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram',
},
],
editLink: {
pattern: ({ relativePath }) => {
if (relativePath.endsWith('/intro.md')) {
return 'https://github.com/zjx0905/axios-miniprogram/edit/main/README.md';
return 'https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/README.md';
}
return `https://github.com/zjx0905/axios-miniprogram/edit/main/docs/pages/${relativePath}`;
return `https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/docs/pages/${relativePath}`;
},
text: '在 GitHub 上编辑此页面',
},
@ -55,9 +58,9 @@ export default defineConfig({
},
footer: {
message:
'根据 <a href="https://github.com/zjx0905/axios-miniprogram/blob/main/LICENSE">MIT License</a> 发布',
'根据 <a href="https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/LICENSE">MIT License</a> 发布',
copyright:
'Copyright © 2020-至今 <a href="https://github.com/zjx0905">zjx0905</a>',
'Copyright © 2020-至今 <a href="https://github.com/zjxxxxxxxxx">zjxxxxxxxxx</a>',
},
},
@ -120,7 +123,6 @@ function sidebar() {
{ text: '创建实例', link: '/advanced/instance' },
{ text: '扩展实例', link: '/advanced/extend' },
{ text: '平台适配器', link: '/advanced/adapter' },
{ text: '派生领域(即将废弃)', link: '/advanced/fork' },
],
collapsed: false,
},
@ -146,11 +148,11 @@ function sidebar() {
items: [
{
text: '行为准则',
link: 'https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md',
},
{
text: '贡献指南',
link: 'https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md',
},
],
},

View File

@ -20,7 +20,6 @@
margin-top: var(--vp-nav-height);
padding-top: 40px !important;
height: calc(100% - var(--vp-nav-height));
border-right: 1px solid var(--vp-c-gutter);
transition: transform 0.3s cubic-bezier(0.19, 1, 0.22, 1) !important;
}
@ -149,11 +148,6 @@
}
.vp-code-group .tabs {
border-top: 1px;
border-left: 1px;
border-right: 1px;
border-bottom: 0;
border-style: solid;
border-color: var(--vp-c-gutter);
}
@ -211,7 +205,6 @@
.language-bash,
.language-ts {
border-radius: 6px;
border: 1px solid var(--vp-c-gutter);
}
.prev-next {

View File

@ -1,4 +1,4 @@
import { linkSync } from 'node:fs';
import { linkSync, unlinkSync } from 'node:fs';
import { resolve } from '../../../scripts/utils';
const readmePath = resolve('README.md');
@ -6,6 +6,9 @@ const introPath = resolve('docs/pages/guide/intro.md');
export function linkIntro() {
try {
linkSync(readmePath, introPath);
} catch {}
unlinkSync(introPath);
} catch {
//
}
linkSync(readmePath, introPath);
}

View File

@ -125,10 +125,6 @@ axios.defaults.adapter = (config) => {
// 默认值200
status: response.statusCode,
// 状态文本
// 默认值:'OK'
statusText: 'OK',
// 响应头
// 默认值:{}
headers: response.header,
@ -146,10 +142,6 @@ axios.defaults.adapter = (config) => {
// 默认值400
status: 400,
// 状态文本
// 默认值:'Fail'
statusText: 'Fail',
// 响应头
// 默认值:{}
headers: {},
@ -180,10 +172,6 @@ axios.defaults.adapter = (config) => {
// 默认值200
status: response.statusCode,
// 状态文本
// 默认值:'OK'
statusText: 'OK',
// 响应头
// 默认值:{}
headers: response.header,
@ -198,10 +186,6 @@ axios.defaults.adapter = (config) => {
// 默认值400
status: 400,
// 状态文本
// 默认值:'Fail'
statusText: 'Fail',
// 响应头
// 默认值:{}
headers: {},
@ -225,10 +209,6 @@ axios.defaults.adapter = (config) => {
// 默认值200
status: response.statusCode,
// 状态文本
// 默认值:'OK'
statusText: 'OK',
// 响应头
// 默认值:{}
headers: response.header,
@ -246,10 +226,6 @@ axios.defaults.adapter = (config) => {
// 默认值400
status: 400,
// 状态文本
// 默认值:'Fail'
statusText: 'Fail',
// 响应头
// 默认值:{}
headers: {},

View File

@ -20,7 +20,7 @@ import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
// 相对地址会进行组合
// baseURL 最终结果为 https://api.com/uesr
// baseURL 最终结果为 https://api.com/user
const instance = axios.extend({
baseURL: 'user',
headers: {

View File

@ -1,228 +0,0 @@
---
title: 派生领域
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
派生新的领域简化 `URL`
:::
::: warning 注意
该接口即将废弃,请使用功能更强的[扩展实例](./extend)。
:::
## 派生领域
可以基于 `axios` 派生领域,配置项 `baseURL` 传相对地址时会和 `axios.defaults.baseURL` 一起组合成完整的服务端地址。
全局默认配置 `axios.defaults` 和派生领域时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成领域默认配置 `domain.defaults`
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
// 相对地址会进行组合
// baseURL 最终结果为 https://api.com/uesr
const domain = axios.fork({
baseURL: 'user',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
// 绝对地址会直接使用
// baseURL 最终结果为 https://api2.com/user
const domain = axios.fork({
baseURL: 'https://api2.com/user',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
```
## 默认配置
可以设置配置项默认值。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
const domain = axios.fork({
baseURL: 'user',
});
domain.defaults.headers.common['Content-Type'] = 'application/json';
domain.defaults.timeout = 1000;
```
## 拦截器
可以使用父级的拦截器,但不支持为领域单独添加拦截器。
基于 axios 派生领域。
```ts
import axios from 'axios-miniprogram';
// 请求拦截器
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
const domain = axios.fork({
baseURL: 'test',
});
// 发送请求时会使用 axios 的请求拦截器和响应拦截器
domain.get('/');
```
基于实例派生领域。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api.com',
});
// 请求拦截器
instance.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
instance.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
const domain = instance.fork({
baseURL: 'test',
});
// 发送请求时会使用 instance 的请求拦截器和响应拦截器
domain.get('/');
```
## 使用方式
可以使用请求方法发送请求。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
const domain = axios.fork({
baseURL: 'user',
});
// 请求的服务端地址 https://api.com/uesr/1
domain
.get('/:id', {
id: 1,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 请求的服务端地址 https://api.com/uesr
domain
.post('/', {
id: 1,
name: 'user',
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 请求的服务端地址 https://api.com/uesr/1
domain
.put('/:id', {
name: 'user',
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 请求的服务端地址 https://api.com/uesr/1
domain
.delete('/:id', {
id: 1,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
- [domain.request(url, config?) | domain.request(config)](/basics/request)
- [domain.options(url, config?)](/method/OPTIONS)
- [domain.get(url, params?, config?)](/method/GET)
- [domain.head(url, params?, config?)](/method/HEAD)
- [domain.post(url, data?, config?)](/method/POST)
- [domain.put(url, data?, config?)](/method/PUT)
- [domain.patch(url, data?, config?)](/method/PATCH)
- [domain.delete(url, params?, config?)](/method/DELETE)
- [domain.trace(url, config?)](/method/TRACE)
- [domain.connect(url, config?)](/method/CONNECT)

View File

@ -99,7 +99,7 @@ const child = instance.extend({
baseURL: 'user',
});
// 请求的服务端地址 https://api2.com/uesr
// 请求的服务端地址 https://api2.com/user
child('/');
```

View File

@ -11,9 +11,10 @@ title: 中间件
## 前言
如果您了解或者使用过[koa](https://github.com/koajs/koa),相信您一定十分了解什么是洋葱模型,中间件该怎么写。
中间件是一个异步函数,接收 `context``next` 两个参数。
`context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其成部分。
`context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其成部分。
- `context.req`:请求配置。
- `context.res`:请求完成后服务端返回的响应体,它的初始值是 `null`,请求完成之后才能对其进行操作。
@ -117,6 +118,6 @@ instance.use(async (ctx, next) => {
});
// 复用父级中间件
// axios request -> instance request -> https://api.com/test/uesr -> instance response -> axios response
// axios request -> instance request -> https://api.com/test/user -> instance response -> axios response
instance('/user');
```

View File

@ -12,7 +12,7 @@ title: 默认配置
## 默认值
在不更改默认配置的情况下,它依然会存在一些默认值,在 [defaults.ts](https://github.com/zjx0905/axios-miniprogram/blob/main/src/defaults.ts) 中定义,大概长下面这样。
在不更改默认配置的情况下,它依然会存在一些默认值,在 [defaults.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/defaults.ts) 中定义,大概长下面这样。
```ts
{
@ -174,4 +174,4 @@ axios.interceptors.response.use((response) => {
2. `headers`、`params` 会分别进行深度合并。
3. 其余属性则会优先从 `config` 取值。
具体配置合并策略请参阅 [mergeConfig.ts](https://github.com/zjx0905/axios-miniprogram/blob/main/src/core/mergeConfig.ts) 。
具体配置合并策略请参阅 [mergeConfig.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/core/mergeConfig.ts) 。

View File

@ -26,7 +26,7 @@ axios('https://api.com/test', {
const {
// 临时文件路径 (本地路径)。没传入 filePath 指定文件存储路径时会返回,下载后的文件会存储到一个临时文件
tempFilePath,
} = response;
} = response.data;
})
.catch((error) => {
// 失败之后做些什么
@ -50,7 +50,7 @@ axios('https://api.com/test', {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response;
} = response.data;
})
.catch((error) => {
// 失败之后做些什么
@ -86,7 +86,7 @@ axios('https://api.com/test', {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response;
} = response.data;
})
.catch((error) => {
// 失败之后做些什么

View File

@ -9,20 +9,20 @@ title: 开始
:::: code-group
```bash [NPM]
$ npm install -D axios-miniprogram
$ npm install axios-miniprogram
```
```bash [YARN]
$ yarn add -D axios-miniprogram
$ yarn add axios-miniprogram
```
```bash [PNPM]
$ pnpm install -D axios-miniprogram
$ pnpm install axios-miniprogram
```
::::
原生小程序也可以直接[下载源码包](https://github.com/zjx0905/axios-miniprogram/releases),但是这样是失去类型提示和 `sourceMap` 定位功能。
原生小程序也可以直接[下载源码包](https://github.com/zjxxxxxxxxx/axios-miniprogram/releases),但是这样是失去类型提示和 `sourceMap` 定位功能。
建议在条件允许的情况下优先使用包管理工具安装的方式,而不是使用下载源码包的方式。

11
examples/taro/.babelrc Normal file
View File

@ -0,0 +1,11 @@
{
"presets": [
[
"taro",
{
"framework": "react",
"ts": true
}
]
]
}

View File

@ -0,0 +1,2 @@
FROM node:16
RUN npm i -g pnpm

View File

@ -0,0 +1,15 @@
{
"setupTasks": [
{
"name": "Install Dependencies",
"command": "pnpm i"
}
],
"tasks": {
"dev": {
"name": "dev",
"command": "pnpm dev:h5",
"runAtStart": true
}
}
}

8
examples/taro/.eslintrc Normal file
View File

@ -0,0 +1,8 @@
{
"extends": ["taro/react"],
"rules": {
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off",
"jsx-quotes": "off"
}
}

7
examples/taro/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
dist/
deploy_versions/
.temp/
.rn_temp/
node_modules/
.DS_Store
.swc

View File

@ -0,0 +1,15 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
logger: {
quiet: false,
stats: true,
},
mini: {},
h5: {
devServer: {
port: 3000,
allowedHosts: 'all',
},
},
} satisfies UserConfigExport;

View File

@ -0,0 +1,102 @@
import { defineConfig, type UserConfigExport } from '@tarojs/cli';
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';
import devConfig from './dev';
import prodConfig from './prod';
// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = {
projectName: 'axios',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
375: 2,
828: 1.81 / 2,
},
sourceRoot: 'src',
outputRoot: `dist/${process.env.TARO_ENV}`,
plugins: [
'@tarojs/plugin-platform-alipay-dd',
'@tarojs/plugin-platform-lark',
'@tarojs/plugin-platform-kwai',
],
defineConstants: {},
copy: {
patterns: [],
options: {},
},
framework: 'react',
compiler: 'webpack5',
cache: {
enable: false, // Webpack 持久化缓存配置建议开启。默认配置请参考https://docs.taro.zone/docs/config-detail#cache
},
mini: {
postcss: {
pxtransform: {
enable: true,
config: {},
},
url: {
enable: true,
config: {
limit: 1024, // 设定转换尺寸上限
},
},
cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
h5: {
publicPath: '/',
staticDirectory: 'static',
output: {
filename: 'js/[name].[hash:8].js',
chunkFilename: 'js/[name].[chunkhash:8].js',
},
miniCssExtractPluginOption: {
ignoreOrder: true,
filename: 'css/[name].[hash].css',
chunkFilename: 'css/[name].[chunkhash].css',
},
postcss: {
autoprefixer: {
enable: true,
config: {},
},
cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
rn: {
appName: 'taroDemo',
postcss: {
cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
},
},
},
};
if (process.env.NODE_ENV === 'development') {
// 本地开发构建配置(不混淆压缩)
return merge({}, baseConfig, devConfig);
}
// 生产构建配置(默认开启压缩混淆等)
return merge({}, baseConfig, prodConfig);
});

View File

@ -0,0 +1,33 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
mini: {},
h5: {
/**
* WebpackChain
* @docs https://github.com/neutrinojs/webpack-chain
*/
// webpackChain (chain) {
// /**
// * 如果 h5 端编译后体积过大,可以使用 webpack-bundle-analyzer 插件对打包体积进行分析。
// * @docs https://github.com/webpack-contrib/webpack-bundle-analyzer
// */
// chain.plugin('analyzer')
// .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
// /**
// * 如果 h5 端首屏加载时间过长,可以使用 prerender-spa-plugin 插件预加载首页。
// * @docs https://github.com/chrisvfritz/prerender-spa-plugin
// */
// const path = require('path')
// const Prerender = require('prerender-spa-plugin')
// const staticDir = path.join(__dirname, '..', 'dist')
// chain
// .plugin('prerender')
// .use(new Prerender({
// staticDir,
// routes: [ '/pages/index/index' ],
// postProcess: (context) => ({ ...context, outputPath: path.join(staticDir, 'index.html') })
// }))
// }
},
} satisfies UserConfigExport;

View File

@ -0,0 +1,79 @@
{
"private": true,
"name": "@examples/taro",
"scripts": {
"build:weapp": "taro build --type weapp",
"build:swan": "taro build --type swan",
"build:alipay": "taro build --type alipay",
"build:tt": "taro build --type tt",
"build:h5": "taro build --type h5",
"build:rn": "taro build --type rn",
"build:qq": "taro build --type qq",
"build:jd": "taro build --type jd",
"build:dd": "taro build --type dd",
"build:lark": "taro build --type lark",
"build:kwai": "taro build --type kwai",
"build:quickapp": "taro build --type quickapp",
"dev:weapp": "npm run build:weapp -- --watch",
"dev:swan": "npm run build:swan -- --watch",
"dev:alipay": "npm run build:alipay -- --watch",
"dev:tt": "npm run build:tt -- --watch",
"dev:h5": "npm run build:h5 -- --watch",
"dev:rn": "npm run build:rn -- --watch",
"dev:qq": "npm run build:qq -- --watch",
"dev:jd": "npm run build:jd -- --watch",
"dev:dd": "npm run build:dd -- --watch",
"dev:lark": "npm run build:lark -- --watch",
"dev:kwai": "npm run build:kwai -- --watch",
"dev:quickapp": "npm run build:quickapp -- --watch"
},
"dependencies": {
"@babel/core": "^7.8.0",
"@babel/runtime": "^7.21.5",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
"@tarojs/cli": "3.6.13",
"@tarojs/components": "3.6.13",
"@tarojs/helper": "3.6.13",
"@tarojs/plugin-framework-react": "3.6.13",
"@tarojs/plugin-platform-alipay": "3.6.13",
"@tarojs/plugin-platform-alipay-dd": "^0.3.0",
"@tarojs/plugin-platform-h5": "3.6.13",
"@tarojs/plugin-platform-jd": "3.6.13",
"@tarojs/plugin-platform-kwai": "^6.0.0",
"@tarojs/plugin-platform-lark": "^1.1.4",
"@tarojs/plugin-platform-qq": "3.6.13",
"@tarojs/plugin-platform-swan": "3.6.13",
"@tarojs/plugin-platform-tt": "3.6.13",
"@tarojs/plugin-platform-weapp": "3.6.13",
"@tarojs/react": "3.6.13",
"@tarojs/runtime": "3.6.13",
"@tarojs/shared": "3.6.13",
"@tarojs/taro": "3.6.13",
"@tarojs/taro-loader": "3.6.13",
"@tarojs/webpack5-runner": "3.6.13",
"@types/react": "^18.0.0",
"@types/webpack-env": "^1.13.6",
"@typescript-eslint/eslint-plugin": "^6.2.0",
"@typescript-eslint/parser": "^6.2.0",
"axios-miniprogram": "latest",
"babel-preset-taro": "3.6.13",
"consola": "^3.2.3",
"eslint": "^8.12.0",
"eslint-config-taro": "3.6.13",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-react": "^7.8.2",
"eslint-plugin-react-hooks": "^4.2.0",
"postcss": "^8.4.18",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-refresh": "^0.11.0",
"stylelint": "^14.4.0",
"tsconfig-paths-webpack-plugin": "^4.0.1",
"typescript": "^5.1.0",
"webpack": "5.78.0"
},
"stackblitz": {
"installDependencies": false,
"startCommand": "pnpm i && pnpm dev:h5"
}
}

View File

@ -0,0 +1,15 @@
{
"miniprogramRoot": "./dist",
"projectname": "taro",
"description": "",
"appid": "touristappid",
"setting": {
"urlCheck": true,
"es6": false,
"enhance": false,
"compileHotReLoad": false,
"postcss": false,
"minified": false
},
"compileType": "miniprogram"
}

View File

@ -0,0 +1,10 @@
{
"miniprogramRoot": "./",
"projectname": "axios-miniprogram",
"appid": "ks739467354825138594",
"libVersion": "0.2.0",
"setting": {
"urlCheck": false
},
"compileType": "miniprogram"
}

View File

@ -0,0 +1,9 @@
{
"miniprogramRoot": "./",
"projectname": "taro",
"appid": "testAppId",
"setting": {
"es6": false,
"minified": false
}
}

View File

@ -0,0 +1,9 @@
export default defineAppConfig({
pages: ['home'],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black',
},
});

5
examples/taro/src/app.ts Normal file
View File

@ -0,0 +1,5 @@
import { PropsWithChildren } from 'react';
export default function App({ children }: PropsWithChildren<any>) {
return children;
}

View File

@ -0,0 +1,13 @@
.page {
padding: 20px;
}
.button {
margin: 20px 0;
}
.code {
padding: 20px;
overflow-x: scroll;
white-space: pre;
}

202
examples/taro/src/home.tsx Normal file
View File

@ -0,0 +1,202 @@
import { View, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import axios, { createAdapter } from 'axios-miniprogram';
import { consola } from 'consola';
import './home.css';
export default function Home() {
const [config, setConfig] = useState<string>('');
const [response, setResponse] = useState<string>('');
const [error, setError] = useState<string>('');
useEffect(() => {
axios.defaults.adapter = createAdapter({
request: Taro.request,
download: Taro.downloadFile,
upload: Taro.uploadFile,
} as any);
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.errorHandler = (err) => {
consola.info('[debug err]', (err as any).response);
setError(`<pre>${JSON.stringify(err, null, 2)}</pre>`);
Taro.hideLoading();
Taro.showToast({
icon: 'none',
title: (err as any).response?.data?.errMsg || '未知错误',
});
return Promise.reject(err);
};
axios.use(async (ctx, next) => {
consola.info('[debug req]', ctx.req);
Taro.showLoading({
title: 'Loading...',
});
setConfig(`<pre>${JSON.stringify(ctx.req, null, 2)}</pre>`);
setError('');
setResponse('');
await next();
consola.info('[debug res]', ctx.res);
setResponse(`<pre>${JSON.stringify(ctx.res, null, 2)}</pre>`);
Taro.hideLoading();
});
}, []);
function getRequest() {
axios.get('/users/:id', {
id: 1,
});
}
function postRequest() {
axios.post('/users', {
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function putRequest() {
axios.put('/users/:id', {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function deleteRequest() {
axios.delete('/users/:id', {
id: 1,
});
}
function downloadRequest() {
axios.get(
'/users/:id',
{
id: 1,
},
{
download: true,
},
);
}
function uploadRequest() {
Taro.chooseImage({
count: 1,
success({ tempFilePaths }) {
axios.post(
'/users',
{
name: 'filename',
filePath: tempFilePaths[0],
fileType: 'image',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
upload: true,
},
);
},
});
}
function errorRequest() {
axios.get('/users/:id', {
id: -1,
});
}
function failRequest() {
axios.get(
'/users',
{},
{
timeout: 0,
},
);
}
return (
<View className="page">
<Button className="button" type="primary" onClick={getRequest}>
GET
</Button>
<Button className="button" type="primary" onClick={postRequest}>
POST
</Button>
<Button className="button" type="primary" onClick={putRequest}>
PUT
</Button>
<Button className="button" type="primary" onClick={deleteRequest}>
DELETE
</Button>
<Button className="button" type="primary" onClick={downloadRequest}>
DOWNLOAD
</Button>
<Button className="button" type="primary" onClick={uploadRequest}>
UPLOAD
</Button>
<Button className="button" type="primary" onClick={errorRequest}>
ERROR
</Button>
<Button className="button" type="primary" onClick={failRequest}>
FAIL
</Button>
config:
<View
className="code"
dangerouslySetInnerHTML={{
__html: config,
}}
></View>
response:
<View
className="code"
dangerouslySetInnerHTML={{
__html: response,
}}
></View>
error:
<View
className="code"
dangerouslySetInnerHTML={{
__html: error,
}}
></View>
</View>
);
}

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="format-detection" content="telephone=no,address=no">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
<title>taro</title>
<script><%= htmlWebpackPlugin.options.script %></script>
</head>
<body>
<div id="app"></div>
</body>
</html>

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"removeComments": false,
"preserveConstEnums": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"outDir": "lib",
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"sourceMap": true,
"baseUrl": ".",
"rootDir": ".",
"jsx": "preserve",
"allowJs": true,
"resolveJsonModule": true,
"typeRoots": ["node_modules/@types"],
"paths": {
"@/*": ["src/*"]
}
},
"include": ["./src", "./types", "./config"],
"compileOnSave": false
}

36
examples/taro/types/global.d.ts vendored Normal file
View File

@ -0,0 +1,36 @@
/// <reference types="@tarojs/taro" />
declare module '*.png';
declare module '*.gif';
declare module '*.jpg';
declare module '*.jpeg';
declare module '*.svg';
declare module '*.css';
declare module '*.less';
declare module '*.scss';
declare module '*.sass';
declare module '*.styl';
declare namespace NodeJS {
interface ProcessEnv {
/** NODE 内置环境变量, 会影响到最终构建生成产物 */
NODE_ENV: 'development' | 'production';
/** 当前构建的平台 */
TARO_ENV:
| 'weapp'
| 'swan'
| 'alipay'
| 'h5'
| 'rn'
| 'tt'
| 'quickapp'
| 'qq'
| 'jd';
/**
* appid
* @description env `TARO_APP_ID`便 appid dist/project.config.json
* @see https://taro-docs.jd.com/docs/next/env-mode-config#特殊环境变量-taro_app_id
*/
TARO_APP_ID: string;
}
}

View File

@ -0,0 +1,2 @@
FROM node:16
RUN npm i -g pnpm

View File

@ -0,0 +1,15 @@
{
"setupTasks": [
{
"name": "Install Dependencies",
"command": "pnpm i"
}
],
"tasks": {
"dev": {
"name": "dev",
"command": "pnpm dev:h5",
"runAtStart": true
}
}
}

21
examples/uni-app/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
*.local
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -0,0 +1,79 @@
{
"private": true,
"name": "@examples/uni-app",
"scripts": {
"dev:app": "uni -p app",
"dev:app-android": "uni -p app-android",
"dev:app-ios": "uni -p app-ios",
"dev:custom": "uni -p",
"dev:h5": "uni",
"dev:h5:ssr": "uni --ssr",
"dev:alipay": "uni -p mp-alipay",
"dev:swan": "uni -p mp-baidu",
"dev:jd": "uni -p mp-jd",
"dev:kwai": "uni -p mp-kuaishou",
"dev:lark": "uni -p mp-lark",
"dev:qq": "uni -p mp-qq",
"dev:tt": "uni -p mp-toutiao",
"dev:dd": "uni -p mp-alipay",
"dev:weapp": "uni -p mp-weixin",
"dev:xhs": "uni -p mp-xhs",
"dev:quickapp-webview": "uni -p quickapp-webview",
"dev:quickapp-webview-huawei": "uni -p quickapp-webview-huawei",
"dev:quickapp-webview-union": "uni -p quickapp-webview-union",
"build:app": "uni build -p app",
"build:app-android": "uni build -p app-android",
"build:app-ios": "uni build -p app-ios",
"build:custom": "uni build -p",
"build:h5": "uni build",
"build:h5:ssr": "uni build --ssr",
"build:alipay": "uni build -p mp-alipay",
"build:swan": "uni build -p mp-baidu",
"build:jd": "uni build -p mp-jd",
"build:kwai": "uni build -p mp-kuaishou",
"build:lark": "uni build -p mp-lark",
"build:qq": "uni build -p mp-qq",
"build:tt": "uni build -p mp-toutiao",
"build:dd": "uni -p mp-alipay",
"build:weapp": "uni build -p mp-weixin",
"build:xhs": "uni build -p mp-xhs",
"build:quickapp-webview": "uni build -p quickapp-webview",
"build:quickapp-webview-huawei": "uni build -p quickapp-webview-huawei",
"build:quickapp-webview-union": "uni build -p quickapp-webview-union"
},
"dependencies": {
"@dcloudio/uni-app": "3.0.0-3080720230703001",
"@dcloudio/uni-app-plus": "3.0.0-3080720230703001",
"@dcloudio/uni-components": "3.0.0-3080720230703001",
"@dcloudio/uni-h5": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-alipay": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-baidu": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-jd": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-kuaishou": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-lark": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-qq": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-toutiao": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-weixin": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-xhs": "3.0.0-alpha-3081220230802001",
"@dcloudio/uni-quickapp-webview": "3.0.0-3080720230703001",
"axios-miniprogram": "latest",
"consola": "^2.15.3",
"vue": "^3.2.45",
"vue-i18n": "^9.1.9"
},
"devDependencies": {
"@dcloudio/types": "^3.3.2",
"@dcloudio/uni-automator": "3.0.0-3080720230703001",
"@dcloudio/uni-cli-shared": "3.0.0-3080720230703001",
"@dcloudio/uni-stacktracey": "3.0.0-3080720230703001",
"@dcloudio/vite-plugin-uni": "3.0.0-3080720230703001",
"@vue/tsconfig": "^0.1.3",
"typescript": "^4.9.4",
"vite": "4.0.4",
"vue-tsc": "^1.0.24"
},
"stackblitz": {
"installDependencies": false,
"startCommand": "pnpm i && pnpm dev:h5"
}
}

View File

@ -0,0 +1,3 @@
<template></template>
<script setup lang="ts"></script>
<style></style>

8
examples/uni-app/src/env.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>;
export default component;
}

View File

@ -0,0 +1,207 @@
<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios-miniprogram';
import consola from 'consola';
const config = ref<string>('');
const response = ref<string>('');
const error = ref<string>('');
axios.defaults.adapter = axios.createAdapter({
request: uni.request as any,
download: uni.downloadFile,
upload: uni.uploadFile as any,
});
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.errorHandler = (err) => {
consola.info('[debug err]', (err as any).response);
error.value = `<pre>${JSON.stringify(err, null, 2)}</pre>`;
uni.hideLoading();
uni.showToast({
icon: 'none',
title: (err as any).response?.data?.errMsg || '未知错误',
});
return Promise.reject(err);
};
axios.use(async (ctx, next) => {
consola.info('[debug req]', ctx.req);
uni.showLoading({
title: 'Loading...',
});
config.value = `<pre>${JSON.stringify(ctx.req, null, 2)}</pre>`;
error.value = '';
response.value = '';
await next();
consola.info('[debug res]', ctx.res);
response.value = `<pre>${JSON.stringify(ctx.res, null, 2)}</pre>`;
uni.hideLoading();
});
function getRequest() {
axios.get('/users/:id', {
id: 1,
});
}
function postRequest() {
axios.post('/users', {
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function putRequest() {
axios.put('/users/:id', {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function deleteRequest() {
axios.delete('/users/:id', {
id: 1,
});
}
function downloadRequest() {
axios.get(
'/users/:id',
{
id: 1,
},
{
download: true,
},
);
}
function uploadRequest() {
uni.chooseImage({
count: 1,
success({ tempFilePaths }) {
axios.post(
'/users',
{
name: 'filename',
filePath: tempFilePaths[0],
fileType: 'image',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
upload: true,
},
);
},
});
}
function errorRequest() {
axios.get('/users/:id', {
id: -1,
});
}
function failRequest() {
axios.get(
'/users',
{},
{
timeout: 0,
},
);
}
defineExpose({
getRequest,
postRequest,
putRequest,
deleteRequest,
config,
response,
error,
});
</script>
<template>
<view class="page">
<button class="button" type="primary" @click="getRequest">GET </button>
<button class="button" type="primary" @click="postRequest">
POST 请求
</button>
<button class="button" type="primary" @click="putRequest">PUT </button>
<button class="button" type="primary" @click="deleteRequest">
DELETE 请求
</button>
<button class="button" type="primary" @click="downloadRequest">
DOWNLOAD 请求
</button>
<button class="button" type="primary" @click="uploadRequest">
UPLOAD 请求
</button>
<button class="button" type="primary" @click="errorRequest">
ERROR 请求
</button>
<button class="button" type="primary" @click="failRequest">
FAIL 请求
</button>
config:
<view class="code" v-html="config"></view>
response:
<view class="code" v-html="response"></view>
error:
<view class="code" v-html="error"></view>
</view>
</template>
<style>
.page {
padding: 20px;
}
.button {
margin: 20px 0;
}
.code {
padding: 20px;
overflow-x: scroll;
white-space: pre;
}
</style>

View File

@ -0,0 +1,8 @@
import { createSSRApp } from 'vue';
import App from './App.vue';
export function createApp() {
const app = createSSRApp(App);
return {
app,
};
}

View File

@ -0,0 +1,72 @@
{
"name": "",
"appid": "",
"description": "",
"versionName": "1.0.0",
"versionCode": "100",
"transformPx": false,
/* 5+App */
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
},
/* */
"modules": {},
/* */
"distribute": {
/* android */
"android": {
"permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios */
"ios": {},
/* SDK */
"sdkConfigs": {}
}
},
/* */
"quickapp": {},
/* */
"mp-weixin": {
"appid": "",
"setting": {
"urlCheck": false
},
"usingComponents": true
},
"mp-alipay": {
"usingComponents": true
},
"mp-baidu": {
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"vueVersion": "3"
}

View File

@ -0,0 +1,9 @@
{
"pages": [{ "path": "home", "style": {} }],
"globalStyle": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "axios-miniprogram",
"navigationBarTextStyle": "black"
}
}

6
examples/uni-app/src/shime-uni.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
export {};
declare module 'vue' {
type Hooks = App.AppInstance & Page.PageInstance;
type ComponentCustomOptions = Hooks;
}

View File

@ -0,0 +1,13 @@
{
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"],
"types": ["@dcloudio/types"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@ -0,0 +1,10 @@
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
// https://vitejs.dev/config/
export default defineConfig({
server: {
port: 3000,
},
plugins: [uni()],
});

View File

@ -1,4 +1,3 @@
declare const uni: any;
declare const wx: any;
declare const my: any;
declare const swan: any;
@ -8,3 +7,4 @@ declare const qh: any;
declare const ks: any;
declare const dd: any;
declare const jd: any;
declare const xhs: any;

View File

@ -1,110 +1,114 @@
{
"name": "axios-miniprogram",
"version": "2.4.1",
"description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。",
"main": "dist/axios-miniprogram.cjs.js",
"module": "dist/axios-miniprogram.esm.js",
"types": "dist/axios-miniprogram.d.ts",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/zjx0905/axios-miniprogram.git"
},
"keywords": [
"axios",
"request",
"mini",
"miniprogram"
],
"author": "zjx0905 <954270063@qq.com>",
"bugs": {
"url": "https://github.com/zjx0905/axios-miniprogram/issues"
},
"homepage": "https://axios-miniprogram.com",
"license": "MIT",
"type": "module",
"engines": {
"node": ">=16",
"pnpm": ">=7"
},
"scripts": {
"cz": "simple-git-hooks && czg",
"build": "esno scripts/build.ts",
"build:assets": "esno scripts/build.assets.ts",
"watch": "pnpm build -a -w",
"release": "esno scripts/release.ts",
"publish:ci": "esno scripts/publish.ts",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"releaselog": "esno scripts/releaselog.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:cov": "vitest run --coverage",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache . --fix",
"docs:dev": "pnpm -C docs dev",
"docs:build": "pnpm -C docs build",
"docs:preview": "pnpm -C docs preview",
"docs:deploy": "esno scripts/docs.deploy.ts",
"start": "esno scripts/start.ts"
},
"devDependencies": {
"@commitlint/cli": "^17.4.4",
"@commitlint/config-conventional": "^17.4.4",
"@rollup/plugin-typescript": "^11.1.0",
"@types/node": "^18.15.5",
"@typescript-eslint/eslint-plugin": "^5.55.0",
"@typescript-eslint/parser": "^5.55.0",
"@vitest/coverage-istanbul": "^0.30.0",
"chalk": "^5.2.0",
"consola": "^2.15.3",
"conventional-changelog-cli": "^2.2.2",
"cz-git": "1.3.8",
"czg": "1.3.8",
"enquirer": "^2.3.6",
"eslint": "^8.36.0",
"esno": "^0.16.3",
"fast-glob": "^3.2.12",
"jszip": "^3.10.1",
"lint-staged": "13.2.0",
"minimist": "^1.2.8",
"prettier": "2.8.5",
"rimraf": "^4.4.0",
"rollup": "^3.20.0",
"rollup-plugin-dts": "^5.3.0",
"rollup-plugin-esbuild": "^5.0.0",
"semver": "^7.3.8",
"simple-git-hooks": "^2.8.1",
"tslib": "^2.5.0",
"typescript": "^5.0.2",
"vitest": "^0.30.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged && pnpm test && pnpm build -a",
"commit-msg": "pnpm commitlint --edit $1"
},
"config": {
"commitizen": {
"path": "node_modules/cz-git"
}
},
"lint-staged": {
"*.{mjs,json}": [
"prettier --write"
],
"*.ts?(x)": [
"eslint",
"prettier --parser=typescript --write"
]
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"esbuild",
"vite"
]
}
}
"name": "axios-miniprogram",
"version": "2.7.2",
"description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。",
"main": "dist/axios-miniprogram.cjs.js",
"module": "dist/axios-miniprogram.esm.js",
"types": "dist/axios-miniprogram.d.ts",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/zjxxxxxxxxx/axios-miniprogram.git"
},
"keywords": [
"axios",
"request",
"mini",
"miniprogram"
],
"author": "zjxxxxxxxxx <954270063@qq.com>",
"bugs": {
"url": "https://github.com/zjxxxxxxxxx/axios-miniprogram/issues"
},
"homepage": "https://axios-miniprogram.com",
"license": "MIT",
"type": "module",
"engines": {
"node": ">=16",
"pnpm": ">=8"
},
"scripts": {
"cz": "simple-git-hooks && czg",
"play": "esno scripts/play.ts",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache . --fix",
"format": "prettier -w {src,test,scripts}/**/*.{ts,tsx,js,jsx}",
"build": "esno scripts/build.ts",
"build:assets": "esno scripts/build.assets.ts",
"dev": "pnpm build -a -w",
"release": "esno scripts/release.ts",
"publish:ci": "esno scripts/publish.ts",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"releaselog": "esno scripts/releaselog.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:cov": "vitest run --coverage",
"docs:dev": "pnpm --filter docs dev",
"docs:build": "pnpm --filter docs build",
"docs:preview": "pnpm --filter docs preview",
"docs:deploy": "esno scripts/docs.deploy.ts"
},
"devDependencies": {
"@commitlint/cli": "^17.7.1",
"@commitlint/config-conventional": "^17.7.0",
"@rollup/plugin-typescript": "^11.1.2",
"@types/minimist": "^1.2.2",
"@types/node": "^18.17.5",
"@types/semver": "^7.5.0",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"@vitest/coverage-istanbul": "^0.30.1",
"chalk": "^5.3.0",
"consola": "^2.15.3",
"conventional-changelog-cli": "^2.2.2",
"cz-git": "1.3.8",
"czg": "1.3.8",
"enquirer": "^2.4.1",
"eslint": "^8.47.0",
"esno": "^0.16.3",
"fast-glob": "^3.3.1",
"jszip": "^3.10.1",
"lint-staged": "13.2.0",
"minimist": "^1.2.8",
"prettier": "2.8.5",
"rimraf": "^4.4.1",
"rollup": "^3.28.0",
"rollup-plugin-dts": "^5.3.1",
"rollup-plugin-esbuild": "^5.0.0",
"semver": "^7.5.4",
"simple-git-hooks": "^2.9.0",
"tslib": "^2.6.1",
"typescript": "^5.1.6",
"vitest": "^0.30.1"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged && pnpm test && pnpm build -a",
"commit-msg": "pnpm commitlint --edit $1"
},
"config": {
"commitizen": {
"path": "node_modules/cz-git"
}
},
"lint-staged": {
"*.{js,json}": [
"prettier --write"
],
"*.ts": [
"eslint",
"prettier --parser=typescript --write"
]
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"esbuild",
"vite",
"eslint"
]
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +1,3 @@
packages:
- docs
- examples/*

View File

@ -29,7 +29,7 @@ function generateZip(inputPath: string, outputPath: string) {
console.log(chalk.cyanBright.bold(`${inputPath} → dist/${outputName}...`));
return new Promise((resolve, reject) => {
const finish = (result) => {
const finish = (result: any) => {
console.log(
`${chalk.green('created')} ${chalk.greenBright.bold(
`dist/${outputName} in ${Date.now() - start}ms\n`,

View File

@ -1,34 +1,34 @@
import minimist from 'minimist'
import consola from 'consola'
import minimist from 'minimist';
import consola from 'consola';
import { distPath, exec } from './utils'
import { checkSize } from './checkSize'
import { safeExit } from './utils'
import { distPath, exec } from './utils';
import { checkSize } from './checkSize';
import { safeExit } from './utils';
const args = minimist(process.argv.slice(2))
const watch = Boolean(args.watch || args.w)
const all = Boolean(args.all || args.a)
const sourceMap = all || Boolean(args.sourceMap || args.s)
const dts = all || Boolean(args.dts || args.d)
const args = minimist(process.argv.slice(2));
const watch = Boolean(args.watch || args.w);
const all = Boolean(args.all || args.a);
const sourceMap = all || Boolean(args.sourceMap || args.s);
const dts = all || Boolean(args.dts || args.d);
main()
main();
function main() {
exec('rimraf dist')
exec('rimraf dist');
consola.info('Rollup')
consola.info('Rollup');
safeExit(() => {
exec(
`rollup -c rollup.config.ts --configPlugin typescript ${
watch ? '-w' : ''
} --environment SOURCE_MAP:${sourceMap},DTS:${dts}`,
)
})
safeExit(() => {
exec(
`rollup -c rollup.config.ts --configPlugin typescript ${
watch ? '-w' : ''
} --environment SOURCE_MAP:${sourceMap},DTS:${dts}`,
);
});
if (!watch) {
checkSize(`${distPath}/**.js`)
}
if (!watch) {
checkSize(`${distPath}/**.js`);
}
console.info('\n')
console.info('\n');
}

48
scripts/play.ts Normal file
View File

@ -0,0 +1,48 @@
import enquirer from 'enquirer';
import consola from 'consola';
import { exec, resolve, safeExit } from './utils';
import { readdirSync } from 'fs';
safeExit(main);
async function main() {
const { framework } = await enquirer.prompt<{ framework: string }>({
type: 'select',
name: 'framework',
message: '请选择跨端框架',
choices: readdirSync(resolve('examples')).filter((i) => i !== '.DS_Store'),
});
const metas = framework === 'taro' ? taroMetas() : uniAppMetas();
const { platform } = await enquirer.prompt<{ platform: string }>({
type: 'select',
name: 'platform',
message: '请选择启动平台',
choices: metas,
});
console.log();
consola.info(
`启动${metas.find((meta) => meta.name === platform)!.message}...`,
);
exec(`pnpm --filter @examples/${framework} dev:${platform}`);
}
function taroMetas() {
return [
{ name: 'h5', message: 'H5' },
{ name: 'weapp', message: '微信小程序' },
{ name: 'swan', message: '百度小程序' },
{ name: 'alipay', message: '支付宝小程序' },
{ name: 'tt', message: '抖音小程序' },
{ name: 'qq', message: 'QQ 小程序' },
{ name: 'jd', message: '京东小程序' },
{ name: 'dd', message: '钉钉小程序' },
{ name: 'lark', message: '飞书小程序' },
{ name: 'kwai', message: '快手小程序' },
];
}
function uniAppMetas() {
return [...taroMetas(), { name: 'xhs', message: '小红书小程序' }];
}

View File

@ -22,7 +22,7 @@ function main() {
}
function generatePublishPkg() {
const publishPkg = {};
const publishPkg: AnyObject = {};
[
'name',

View File

@ -1,5 +1,5 @@
import { writeFileSync } from 'node:fs';
import semver from 'semver';
import semver, { ReleaseType } from 'semver';
import enquirer from 'enquirer';
import consola from 'consola';
import { exec, pkgPath, getPkgJSON, resolve } from './utils';
@ -27,10 +27,10 @@ async function main() {
exec(`git tag -a v${version} -m "v${version}"`);
consola.info('Git push');
exec('git push');
exec('git push -f');
consola.info('Git push tag');
exec(`git push origin v${version}`);
exec(`git push -f origin v${version}`);
}
function checkBranch() {
@ -103,7 +103,9 @@ function createReleases() {
];
const releases: string[] = [];
for (const [type, preid] of types) {
releases.push(`${type} (${semver.inc(currentVersion, type, preid)})`);
releases.push(
`${type} (${semver.inc(currentVersion, type as ReleaseType, preid)})`,
);
}
return releases;
}

View File

@ -1,29 +0,0 @@
import enquirer from 'enquirer'
import { exec } from './utils'
import { safeExit } from './utils'
const metas = [
{ name: 'weapp', message: '微信小程序' },
{ name: 'swan', message: '百度小程序' },
{ name: 'alipay', message: '支付宝小程序' },
{ name: 'tt', message: '抖音小程序' },
{ name: 'qq', message: 'QQ 小程序' },
{ name: 'jd', message: '京东小程序' },
{ name: 'dd', message: '钉钉小程序' },
{ name: 'lark', message: '飞书小程序' },
{ name: 'kwai', message: '快手小程序' },
{ name: 'h5', message: 'H5' },
]
safeExit(main)
async function main() {
const { platform } = await enquirer.prompt<{ platform: string }>({
type: 'select',
name: 'platform',
message: '请选择启动平台',
choices: metas,
})
exec(`pnpm -C example dev:${platform}`)
}

View File

@ -29,13 +29,11 @@ export function noop() {
export function mockResponse(
status = 200,
statusText = 'OK',
headers: AnyObject = {},
data: AnyObject = {},
) {
return {
status,
statusText,
headers,
data,
};
@ -72,13 +70,13 @@ function mockAdapterBase(
if (!canceled) {
switch (type) {
case 'success':
config.success(mockResponse(200, 'OK', headers, data));
config.success(mockResponse(200, headers, data));
break;
case 'error':
config.success(mockResponse(500, 'ERROR', headers, data));
config.success(mockResponse(500, headers, data));
break;
case 'fail':
config.fail(mockResponse(400, 'FAIL', headers, data));
config.fail(mockResponse(400, headers, data));
break;
}

View File

@ -1,39 +1,40 @@
import { isPromise } from 'node:util/types'
import path from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { ExecSyncOptions, execSync } from 'node:child_process'
import consola from 'consola'
import { isPromise } from 'node:util/types';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { ExecSyncOptions, execSync } from 'node:child_process';
import consola from 'consola';
export const __dirname = fileURLToPath(new URL('../', import.meta.url))
export const require = createRequire(import.meta.url)
export const pkgPath = path.resolve(__dirname, 'package.json')
export const distPath = path.resolve(__dirname, 'dist')
export const __dirname = fileURLToPath(new URL('../', import.meta.url));
export const require = createRequire(import.meta.url);
export const pkgPath = path.resolve(__dirname, 'package.json');
export const distPath = path.resolve(__dirname, 'dist');
export const resolve = (...paths: string[]) => path.resolve(__dirname, ...paths)
export const resolve = (...paths: string[]) =>
path.resolve(__dirname, ...paths);
export const exec = (command: string, options: ExecSyncOptions = {}) =>
execSync(command, {
stdio: 'inherit',
encoding: 'utf-8',
...options,
})
execSync(command, {
stdio: 'inherit',
encoding: 'utf-8',
...options,
});
export const getPkgJSON = () => require(pkgPath)
export const getPkgJSON = () => require(pkgPath);
export function safeExit(run: () => unknown) {
try {
const p = run()
try {
const p = run();
if (isPromise(p)) {
return p.catch(exit)
}
} catch {
exit()
}
if (isPromise(p)) {
return p.catch(exit);
}
} catch {
exit();
}
}
function exit() {
consola.error('已退出')
process.exit()
consola.error('已退出');
process.exit();
}

View File

@ -1,6 +1,6 @@
import { isFunction, isPlainObject } from '../helpers/isTypes';
import { isFunction, isPlainObject } from '../helpers/types';
import { assert } from '../helpers/error';
import { origIgnore } from '../helpers/ignore';
import { ignore, orgIgnore } from '../helpers/ignore';
import {
AxiosProgressEvent,
AxiosRequestFormData,
@ -44,10 +44,6 @@ export interface AxiosAdapterResponse extends AnyObject {
*
*/
status?: number;
/**
*
*/
statusText?: string;
/**
*
*/
@ -66,10 +62,6 @@ export interface AxiosAdapterResponseError extends AnyObject {
*
*/
status?: number;
/**
*
*/
statusText?: string;
/**
*
*/
@ -111,11 +103,11 @@ export interface AxiosAdapterRequestConfig extends AnyObject {
/**
*
*/
dataType?: 'json' | '其他';
dataType?: string;
/**
*
*/
responseType?: 'text' | 'arraybuffer';
responseType?: string;
/**
* 60000
*/
@ -170,11 +162,11 @@ export interface AxiosAdapterUploadOptions
extends AxiosAdapterBaseOptions,
AxiosRequestFormData {
/**
* [fileName name](https://open.dingtalk.com/document/orgapp/dd-upload-objects#title-ngk-rr1-eow)
* [fileName name](https://open.dingtalk.com/document/orgapp/dd-upload-objects#title-ngk-rr1-eow)
*/
fileName: string;
/**
* |
* |
*/
fileType?: 'image' | 'video' | 'audie';
/**
@ -269,82 +261,134 @@ export function createAdapter(platform: AxiosAdapterPlatform) {
function transformOptions(
config: AxiosAdapterRequestConfig,
): AxiosAdapterBaseOptions {
const { success, fail } = config;
return {
...config,
header: config.headers,
success(response: AxiosAdapterResponse) {
transformResponse(response);
config.success(response);
success(rawRes: AxiosAdapterResponse) {
const response = transformResponse(rawRes) as AxiosAdapterResponse;
success(response);
},
fail(responseError: AxiosAdapterResponseError) {
responseError.data = {
errMsg: responseError.errMsg,
errno: responseError.errno,
fail(rawErr: AxiosAdapterResponseError) {
const responseError = {
...transformResponse(rawErr),
data: {
errno:
// 微信 | 飞书新规范
rawErr.errno ??
// 支付宝 | 钉钉
rawErr.error ??
// 百度 | 360 | 飞书
rawErr.errCode ??
// 抖音
rawErr.errNo,
errMsg:
// 飞书新规范
rawErr.errString ??
// 微信 | 支付宝 | 百度 | 抖音 | QQ | 360 | 飞书
rawErr.errMsg ??
// 钉钉
rawErr.errorMessage,
},
};
transformResponse(responseError);
config.fail(responseError);
fail(responseError);
},
};
}
function transformResponse(
response: AxiosAdapterResponse | AxiosAdapterResponseError,
rawRes: AxiosAdapterResponse | AxiosAdapterResponseError,
) {
response.status = response.status ?? response.statusCode;
response.headers = response.headers ?? response.header;
return {
...ignore(
rawRes,
'statusCode',
'header',
origIgnore(response, ['statusCode', 'errMsg', 'errno', 'header']);
// 错误码
'errno',
'error',
'errCode',
'errNo',
// 错误消息
'errMsg',
'errorMessage',
'errString',
),
status: rawRes.status ?? rawRes.statusCode,
headers: rawRes.headers ?? rawRes.header,
};
}
function processRequest(
request: AxiosAdapterRequest,
baseOptions: AxiosAdapterBaseOptions,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
return request(baseOptions);
}
function processUpload(
upload: AxiosAdapterUpload,
baseOptions: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
const options = baseOptions as AxiosAdapterUploadOptions;
const { name, filePath, fileType, ...formData } = options.data as AnyObject;
options.name = name;
options.fileName = name;
options.filePath = filePath;
options.fileType = fileType;
options.formData = formData;
origIgnore(options, ['params', 'data']);
return upload(options);
return request(rawOpts);
}
function processDownload(
download: AxiosAdapterDownload,
baseOptions: AxiosAdapterBaseOptions,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
const options = baseOptions as AxiosAdapterDownloadOptions;
const options = rawOpts as AxiosAdapterDownloadOptions;
const { params, success } = options;
options.filePath = params?.filePath;
options.success = (response) => {
response.data = {
filePath: response.filePath,
tempFilePath:
response.tempFilePath ||
// response.apFilePath 为支付宝小程序基础库小于 2.7.23 的特有属性。
response.apFilePath,
options.success = (rawRes) => {
const response = {
...ignore(rawRes, 'tempFilePath', 'apFilePath', 'filePath', 'fileSize'),
data: {
filePath: rawRes.filePath,
tempFilePath:
rawRes.tempFilePath ??
// 支付宝
rawRes.apFilePath,
fileSize:
// 飞书
rawRes.fileSize,
},
};
origIgnore(response, ['tempFilePath', 'apFilePath', 'filePath']);
success(response);
};
origIgnore(options, ['params']);
orgIgnore(options, ['params']);
return download(options);
}
function processUpload(
upload: AxiosAdapterUpload,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
const options = rawOpts as AxiosAdapterUploadOptions;
const { data, success } = options;
const { name, filePath, fileType, ...formData } = data as AnyObject;
options.name = name;
options.filePath = filePath;
options.formData = formData;
// 支付宝 | 钉钉
options.fileName = name;
// 支付宝 | 钉钉
options.fileType = fileType;
options.success = (rawRes) => {
const response = { ...rawRes };
if (options.responseType === 'text' && options.dataType === 'json') {
try {
response.data = JSON.parse(rawRes.data);
} catch {
//
}
}
success(response);
};
orgIgnore(options, ['params', 'data']);
return upload(options);
}
return adapter;
}

View File

@ -1,4 +1,4 @@
import { isFunction, isPlainObject } from '../helpers/isTypes';
import { isFunction, isPlainObject } from '../helpers/types';
import { AxiosAdapterPlatform, createAdapter } from './createAdapter';
/**
@ -6,58 +6,71 @@ import { AxiosAdapterPlatform, createAdapter } from './createAdapter';
*/
export function getDefaultAdapter() {
const platform = revisePlatformApiNames(getPlatform());
if (!isPlatform(platform)) {
return;
if (isPlatform(platform)) {
return createAdapter(platform);
}
function getPlatform() {
const undef = 'undefined';
if (typeof uni !== undef) {
return {
request: uni.request,
downloadFile: uni.downloadFile,
uploadFile: uni.uploadFile,
};
} else if (typeof wx !== undef) {
return wx;
} else if (typeof my !== undef) {
return my;
} else if (typeof swan !== undef) {
return swan;
} else if (typeof tt !== undef) {
return tt;
} else if (typeof qq !== undef) {
return qq;
} else if (typeof qh !== undef) {
return qh;
} else if (typeof ks !== undef) {
return ks;
} else if (typeof dd !== undef) {
return dd;
} else if (typeof jd !== undef) {
return jd;
}
}
function revisePlatformApiNames(platform?: AnyObject) {
return (
platform && {
request: platform.request ?? platform.httpRequest,
upload: platform.upload ?? platform.uploadFile,
download: platform.download ?? platform.downloadFile,
}
);
}
function isPlatform(value: any): value is AxiosAdapterPlatform {
return (
isPlainObject(value) &&
isFunction(value.request) &&
isFunction(value.upload) &&
isFunction(value.download)
);
}
return createAdapter(platform);
}
function getPlatform() {
const undef = 'undefined';
// 微信小程序
if (typeof wx !== undef) {
return wx;
}
// 支付宝小程序
else if (typeof my !== undef) {
return my;
}
// 百度小程序
else if (typeof swan !== undef) {
return swan;
}
// 抖音小程序 | 飞书小程序
else if (typeof tt !== undef) {
return tt;
}
// QQ 小程序
else if (typeof qq !== undef) {
return qq;
}
// 360 小程序
else if (typeof qh !== undef) {
return qh;
}
// 快手小程序
else if (typeof ks !== undef) {
return ks;
}
// 钉钉小程序
else if (typeof dd !== undef) {
return dd;
}
// 京东小程序
else if (typeof jd !== undef) {
return jd;
}
// 小红书小程序
else if (typeof xhs !== undef) {
return xhs;
}
}
function revisePlatformApiNames(platform?: AnyObject) {
if (platform) {
return {
request: platform.request ?? platform.httpRequest,
upload: platform.upload ?? platform.uploadFile,
download: platform.download ?? platform.downloadFile,
};
}
}
function isPlatform(value: any): value is AxiosAdapterPlatform {
return (
isPlainObject(value) &&
isFunction(value.request) &&
isFunction(value.upload) &&
isFunction(value.download)
);
}

View File

@ -3,7 +3,7 @@ import {
WITH_DATA_METHODS,
WITH_PARAMS_METHODS,
} from '../constants/methods';
import { isString } from '../helpers/isTypes';
import { isString } from '../helpers/types';
import { dispatchRequest } from '../request/dispatchRequest';
import { CancelToken } from '../request/cancel';
import { AxiosTransformer } from '../request/transformData';
@ -354,14 +354,16 @@ export interface AxiosConstructor {
export default class Axios {
/**
* @internal
*
*
*/
#parent?: Axios;
private declare parent?: Axios;
/**
*
*/
defaults: AxiosRequestConfig;
declare defaults: AxiosRequestConfig;
/**
*
@ -378,71 +380,64 @@ export default class Axios {
};
/**
* @internal
*
*
*/
#middleware = new MiddlewareManager();
private middleware = new MiddlewareManager();
/**
* options
*/
options!: AxiosRequestMethodFn;
declare options: AxiosRequestMethodFn;
/**
* get
*/
get!: AxiosRequestMethodFnWithParams;
declare get: AxiosRequestMethodFnWithParams;
/**
* head
*/
head!: AxiosRequestMethodFnWithParams;
declare head: AxiosRequestMethodFnWithParams;
/**
* post
*/
post!: AxiosRequestMethodFnWithData;
declare post: AxiosRequestMethodFnWithData;
/**
* put
*/
put!: AxiosRequestMethodFnWithData;
declare put: AxiosRequestMethodFnWithData;
/**
* patch
*/
patch!: AxiosRequestMethodFnWithData;
declare patch: AxiosRequestMethodFnWithData;
/**
* delete
*/
delete!: AxiosRequestMethodFnWithParams;
declare delete: AxiosRequestMethodFnWithParams;
/**
* trace
*/
trace!: AxiosRequestMethodFn;
declare trace: AxiosRequestMethodFn;
/**
* connect
*/
connect!: AxiosRequestMethodFn;
declare connect: AxiosRequestMethodFn;
/**
*
*
* @param middleware
*/
use: (middleware: MiddlewareCallback) => MiddlewareManager;
/**
*
* @param config
* @param parent
*/
constructor(config: AxiosRequestConfig, parent?: Axios) {
this.defaults = config;
this.#parent = parent;
this.use = this.#middleware.use;
this.parent = parent;
}
/**
@ -462,7 +457,7 @@ export default class Axios {
'get') as AxiosRequestMethod;
const requestHandler = {
resolved: this.#handleRequest,
resolved: this.handleRequest,
};
const errorHandler = {
rejected: config.errorHandler,
@ -472,12 +467,12 @@ export default class Axios {
| Partial<Interceptor<AxiosResponse>>
)[] = [];
this.#eachRequestInterceptors((requestInterceptor) => {
chain.unshift(requestInterceptor);
this.eachInterceptors('request', (interceptor) => {
chain.unshift(interceptor);
});
chain.push(requestHandler);
this.#eachResponseInterceptors((responseInterceptor) => {
chain.push(responseInterceptor);
this.eachInterceptors('response', (interceptor) => {
chain.push(interceptor);
});
chain.push(errorHandler);
@ -492,38 +487,81 @@ export default class Axios {
) as Promise<AxiosResponse>;
};
#eachRequestInterceptors(executor: InterceptorExecutor<AxiosRequestConfig>) {
this.interceptors.request.forEach(executor);
if (this.#parent) {
this.#parent.#eachRequestInterceptors(executor);
/**
* @internal
*/
private eachInterceptors<T extends 'request' | 'response'>(
type: T,
executor: InterceptorExecutor<
T extends 'request' ? AxiosRequestConfig : AxiosResponse
>,
) {
// @ts-ignore
this.interceptors[type].forEach(executor);
if (this.parent) {
this.parent.eachInterceptors(type, executor);
}
}
#eachResponseInterceptors(executor: InterceptorExecutor<AxiosResponse>) {
this.interceptors.response.forEach(executor);
if (this.#parent) {
this.#parent.#eachResponseInterceptors(executor);
}
}
/**
*
*
* 1
* ```ts
* axios.use(async function middleware(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* });
* ```
*
* 2
* ```ts
* axios
* .use(async function middleware1(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* })
* .use(async function middleware2(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* });
* ```
*/
use = (middleware: MiddlewareCallback) => {
this.middleware.use(middleware);
return this;
};
#handleRequest = async (config: AxiosRequestConfig) => {
const ctx = this.#middleware.createContext(config);
await this.#run(ctx, this.#handleResponse);
/**
* @internal
*/
private handleRequest = async (config: AxiosRequestConfig) => {
const ctx = this.middleware.createContext(config);
await this.run(ctx, this.handleResponse);
return ctx.res as AxiosResponse;
};
#handleResponse = async (ctx: MiddlewareContext) => {
/**
* @internal
*/
private async handleResponse(ctx: MiddlewareContext) {
ctx.res = await dispatchRequest(ctx.req);
};
}
#run = (
/**
* @internal
*/
private run = (
ctx: MiddlewareContext,
respond: MiddlewareCallback,
): Promise<void> => {
if (!this.#parent) {
return this.#middleware.run(ctx, respond);
if (!this.parent) {
return this.middleware.run(ctx, respond);
}
return this.#middleware.enhanceRun(this.#parent.#run)(ctx, respond);
return this.middleware.enhanceRun(this.parent.run)(ctx, respond);
};
}
@ -537,11 +575,11 @@ for (const method of PLAIN_METHODS) {
for (const method of WITH_PARAMS_METHODS) {
Axios.prototype[method] = function processRequestMethodWithParams(
url,
params = {},
params,
config = {},
) {
config.method = method;
config.params = deepMerge(params, config.params ?? {});
config.params = deepMerge(params, config.params);
return this.request(url, config);
};
}

View File

@ -29,20 +29,26 @@ export interface InterceptorExecutor<T = unknown> {
*/
export default class InterceptorManager<T = unknown> {
/**
* @internal
*
*
*/
#id = 0;
private id = 0;
/**
* @internal
*
*
*/
#interceptors = new Map<number, Interceptor<T>>();
private interceptors = new Map<number, Interceptor<T>>();
/**
* @internal
*
*
*/
get size() {
return this.#interceptors.size;
return this.interceptors.size;
}
/**
@ -56,12 +62,12 @@ export default class InterceptorManager<T = unknown> {
resolved: InterceptorResolved<T>,
rejected?: InterceptorRejected<T>,
): number {
this.#interceptors.set(++this.#id, {
this.interceptors.set(++this.id, {
resolved,
rejected,
});
return this.#id;
return this.id;
}
/**
@ -70,22 +76,24 @@ export default class InterceptorManager<T = unknown> {
* @param id
*/
eject(id: number): boolean {
return this.#interceptors.delete(id);
return this.interceptors.delete(id);
}
/**
*
*/
clear() {
this.#interceptors.clear();
this.interceptors.clear();
}
/**
* @internal
*
*
*
* @param executor
*/
forEach(executor: InterceptorExecutor<T>): void {
this.#interceptors.forEach(executor);
this.interceptors.forEach(executor);
}
}

View File

@ -1,5 +1,5 @@
import { assert } from '../helpers/error';
import { isFunction } from '../helpers/isTypes';
import { isFunction } from '../helpers/types';
import { AxiosRequestConfig, AxiosResponse } from './Axios';
export interface MiddlewareNext {
@ -34,22 +34,23 @@ export interface MiddlewareCallback {
*/
export default class MiddlewareManager {
/**
* @internal
*
*
*/
#middlewares: MiddlewareCallback[] = [];
private middlewares: MiddlewareCallback[] = [];
/**
*
*
* @param middleware
*/
use = (middleware: MiddlewareCallback) => {
use(middleware: MiddlewareCallback) {
assert(isFunction(middleware), 'middleware 不是一个 function');
this.#middlewares.push(middleware);
return this;
};
this.middlewares.push(middleware);
}
/**
* @internal
*
*
*/
createContext(config: AxiosRequestConfig): MiddlewareContext {
@ -60,13 +61,15 @@ export default class MiddlewareManager {
}
/**
*
* @internal
*
*
*
* @param ctx
* @param respond
*/
run(ctx: MiddlewareContext, respond: MiddlewareCallback) {
const middlewares = [...this.#middlewares, respond];
const middlewares = [...this.middlewares, respond];
async function next() {
await middlewares.shift()!(ctx, next);
}
@ -74,7 +77,9 @@ export default class MiddlewareManager {
}
/**
*
* @internal
*
*
*
* @param enhancer
*/

View File

@ -1,3 +1,4 @@
import { dynamicURL } from '../helpers/dynamicURL';
import { combineURL } from '../helpers/combineURL';
import { transformURL } from '../helpers/transformURL';
import Axios, {
@ -43,21 +44,17 @@ export interface AxiosInstance extends AxiosRequest, Axios {
* @param config
*/
extend(config: AxiosRequestConfig): AxiosInstance;
/**
*
*
* @param config
*
* @deprecated 使 extend fork
*/
fork(config: AxiosRequestConfig): AxiosInstance;
}
export function createInstance(defaults: AxiosRequestConfig, parent?: Axios) {
const context = new Axios(defaults, parent);
export function createInstance(
defaults: AxiosRequestConfig,
parentContext?: Axios,
) {
const context = new Axios(defaults, parentContext);
const instance = context.request as AxiosInstance;
instance.getUri = function getUri(config) {
config.url = dynamicURL(config.url!, config.params, config.data);
return transformURL(mergeConfig(defaults, config));
};
instance.create = function create(config) {
@ -67,7 +64,6 @@ export function createInstance(defaults: AxiosRequestConfig, parent?: Axios) {
config.baseURL = combineURL(defaults.baseURL, config.baseURL);
return createInstance(mergeConfig(defaults, config), context);
};
instance.fork = instance.extend;
Object.assign(instance, context);
Object.setPrototypeOf(instance, Axios.prototype);

View File

@ -1,4 +1,4 @@
import { isUndefined, isPlainObject } from '../helpers/isTypes';
import { isUndefined, isPlainObject } from '../helpers/types';
import { deepMerge } from '../helpers/deepMerge';
import { AxiosRequestConfig } from './Axios';
@ -39,12 +39,10 @@ export function mergeConfig(
}
// 深度合并 config1 和 config2 中的对象
else if (deepMergeConfigMap[key]) {
if (isPlainObject(val1) && isPlainObject(val2)) {
config[key] = deepMerge(val1, val2);
if (isPlainObject(val1)) {
config[key] = deepMerge(val1, isPlainObject(val2) ? val2 : {});
} else if (isPlainObject(val2)) {
config[key] = val2;
} else if (isPlainObject(val1)) {
config[key] = val1;
config[key] = deepMerge(val2, {});
}
}
// 优先从 config2 中取值,如果没有值就从 config1 中取值

View File

@ -1,4 +1,4 @@
import { isArray, isDate, isNull, isPlainObject, isUndefined } from './isTypes';
import { isArray, isDate, isNull, isPlainObject, isUndefined } from './types';
export function buildURL(
url = '',

View File

@ -1,4 +1,4 @@
import { isPlainObject } from './isTypes';
import { isPlainObject } from './types';
export function deepMerge<T extends AnyObject>(...objs: (T | undefined)[]): T {
const result: AnyObject = {};

View File

@ -1,11 +1,15 @@
const dynamicRE = /\/:([^/]+)/g;
import { AxiosRequestData } from '../core/Axios';
import { ensureObject } from './ensureObject';
const dynamicRE = /\/:([^/?]+)/g;
export function dynamicURL(
url: string,
params: AnyObject = {},
data: AnyObject = {},
data: AxiosRequestData = {},
) {
const dataObject = ensureObject(data);
return url.replace(dynamicRE, (_, $2) => {
const value = params[$2] ?? data[$2];
const value = params[$2] ?? dataObject[$2];
if ($2 in params) {
delete params[$2];
}

View File

@ -0,0 +1,5 @@
import { isPlainObject } from './types';
export function ensureObject(value?: any) {
return isPlainObject(value) ? value : {};
}

View File

@ -0,0 +1,68 @@
const httpStatusCodes = {
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
103: 'Early Hints',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
208: 'Already Reported',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
307: 'Temporary Redirect',
308: 'Permanent Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Content Too Large',
414: 'URI Too Long',
415: 'Unsupported Media Type',
416: 'Range Not Satisfiable',
417: 'Expectation Failed',
418: "I'm a teapot",
421: 'Misdirected Request',
422: 'Unprocessable Content',
423: 'Locked',
424: 'Failed Dependency',
425: 'Too Early',
426: 'Upgrade Required',
428: 'Precondition Required',
429: 'Too Many Requests',
431: 'Request Header Fields Too Large',
451: 'Unavailable For Legal Reasons',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
508: 'Loop Detected',
510: 'Not Extended',
511: 'Network Authentication Required',
} as const;
export function getHttpStatusText(status: number) {
// @ts-ignore
return httpStatusCodes[status] || 'Unknown';
}

View File

@ -9,7 +9,7 @@ export function ignore<T extends AnyObject, K extends keyof T>(
...keys: K[]
): Omit<T, K> {
const res = { ...obj };
origIgnore(res, keys);
orgIgnore(res, keys);
return res;
}
@ -19,7 +19,7 @@ export function ignore<T extends AnyObject, K extends keyof T>(
* @param obj
* @param keys
*/
export function origIgnore(obj: AnyObject, keys: PropertyKey[]) {
export function orgIgnore(obj: AnyObject, keys: PropertyKey[]) {
for (const key of keys) {
delete obj[key as string | number];
}

View File

@ -1,15 +1,8 @@
import { AxiosRequestConfig } from '../core/Axios'
import { isPlainObject } from './isTypes'
import { buildURL } from './buildURL'
import { combineURL } from './combineURL'
import { dynamicURL } from './dynamicURL'
import { AxiosRequestConfig } from '../core/Axios';
import { buildURL } from './buildURL';
import { combineURL } from './combineURL';
export function transformURL(config: AxiosRequestConfig) {
const fullPath = dynamicURL(
combineURL(config.baseURL, config.url),
config.params,
isPlainObject(config.data) ? config.data : {},
)
return buildURL(fullPath, config.params, config.paramsSerializer)
const fullPath = combineURL(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}

View File

@ -44,21 +44,27 @@ export function isCancel(value: unknown): value is Cancel {
}
export class CancelToken {
#reason?: Cancel;
/**
* @internal
*/
private declare reason?: Cancel;
onCancel: Promise<Cancel>['then'];
/**
* @internal
*/
declare onCancel: Promise<Cancel>['then'];
constructor(executor: CancelExecutor) {
let action!: CancelAction;
const promise = new Promise<Cancel>((resolve) => {
action = (message) => {
if (this.#reason) {
if (this.reason) {
return;
}
this.#reason = new Cancel(message);
this.reason = new Cancel(message);
resolve(this.#reason);
resolve(this.reason);
};
});
@ -79,9 +85,12 @@ export class CancelToken {
};
}
/**
* @internal
*/
throwIfRequested(): void {
if (this.#reason) {
throw this.#reason;
if (this.reason) {
throw this.reason;
}
}
}

View File

@ -19,12 +19,9 @@ class AxiosError extends Error {
request: AxiosAdapterPlatformTask,
) {
super(message);
this.config = config;
this.request = request;
this.response = response;
Object.setPrototypeOf(this, AxiosError.prototype);
}
}

View File

@ -1,12 +1,13 @@
import { WITH_DATA_RE } from '../constants/methods'
import { isFunction, isString } from '../helpers/isTypes'
import { assert } from '../helpers/error'
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios'
import { Cancel, isCancel, isCancelToken } from './cancel'
import { flattenHeaders } from './flattenHeaders'
import { AxiosTransformer, transformData } from './transformData'
import { request } from './request'
import { AxiosErrorResponse } from './createError'
import { WITH_DATA_RE } from '../constants/methods';
import { isFunction, isString } from '../helpers/types';
import { assert } from '../helpers/error';
import { dynamicURL } from '../helpers/dynamicURL';
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios';
import { Cancel, isCancel, isCancelToken } from './cancel';
import { flattenHeaders } from './flattenHeaders';
import { AxiosTransformer, transformData } from './transformData';
import { request } from './request';
import { AxiosErrorResponse } from './createError';
/**
*
@ -16,51 +17,52 @@ import { AxiosErrorResponse } from './createError'
* @param config
*/
export function dispatchRequest(config: AxiosRequestConfig) {
throwIfCancellationRequested(config)
throwIfCancellationRequested(config);
assert(isFunction(config.adapter), 'adapter 不是一个 function')
assert(isString(config.url), 'url 不是一个 string')
assert(isString(config.method), 'method 不是一个 string')
assert(isFunction(config.adapter), 'adapter 不是一个 function');
assert(isString(config.url), 'url 不是一个 string');
assert(isString(config.method), 'method 不是一个 string');
config.headers = flattenHeaders(config)
config.url = dynamicURL(config.url!, config.params, config.data);
config.headers = flattenHeaders(config);
// 可以携带 data 的请求方法,转换 data
// 否则,删除 data
if (WITH_DATA_RE.test(config.method!)) {
dataTransformer(config, config.transformRequest)
} else {
delete config.data
}
// 可以携带 data 的请求方法,转换 data
// 否则,删除 data
if (WITH_DATA_RE.test(config.method!)) {
dataTransformer(config, config.transformRequest);
} else {
delete config.data;
}
function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config)
dataTransformer(response, config.transformResponse)
function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config);
dataTransformer(response, config.transformResponse);
return response
}
return response;
}
function onError(error: Cancel | AxiosErrorResponse) {
if (!isCancel(error)) {
throwIfCancellationRequested(config)
dataTransformer(error.response, config.transformResponse)
}
function onError(error: Cancel | AxiosErrorResponse) {
if (!isCancel(error)) {
throwIfCancellationRequested(config);
dataTransformer(error.response, config.transformResponse);
}
return Promise.reject(error)
}
return Promise.reject(error);
}
function dataTransformer<TData = unknown>(
obj: { data?: TData; headers?: AnyObject },
fn?: AxiosTransformer<TData>,
) {
obj.data = transformData(obj.data, obj.headers, fn)
}
function dataTransformer<TData = unknown>(
obj: { data?: TData; headers?: AnyObject },
fn?: AxiosTransformer<TData>,
) {
obj.data = transformData(obj.data, obj.headers, fn);
}
return request(config).then(onSuccess, onError)
return request(config).then(onSuccess, onError);
}
function throwIfCancellationRequested(config: AxiosRequestConfig) {
const { cancelToken } = config
if (isCancelToken(cancelToken)) {
cancelToken.throwIfRequested()
}
const { cancelToken } = config;
if (isCancelToken(cancelToken)) {
cancelToken.throwIfRequested();
}
}

View File

@ -1,20 +1,21 @@
import { isFunction, isPlainObject } from '../helpers/isTypes'
import { transformURL } from '../helpers/transformURL'
import { isFunction, isPlainObject } from '../helpers/types';
import { transformURL } from '../helpers/transformURL';
import { getHttpStatusText } from '../helpers/getHttpStatusText';
import {
AxiosRequestConfig,
AxiosResponse,
AxiosResponseError,
} from '../core/Axios'
AxiosRequestConfig,
AxiosResponse,
AxiosResponseError,
} from '../core/Axios';
import {
AxiosAdapterRequestConfig,
AxiosAdapterResponse,
AxiosAdapterResponseError,
AxiosAdapterPlatformTask,
AxiosAdapterRequestMethod,
} from '../adpater/createAdapter'
import { isCancelToken } from './cancel'
import { AxiosErrorResponse, createError } from './createError'
import { generateType } from './generateType'
AxiosAdapterRequestConfig,
AxiosAdapterResponse,
AxiosAdapterResponseError,
AxiosAdapterPlatformTask,
AxiosAdapterRequestMethod,
} from '../adpater/createAdapter';
import { isCancelToken } from './cancel';
import { AxiosErrorResponse, createError } from './createError';
import { generateType } from './generateType';
/**
*
@ -24,99 +25,101 @@ import { generateType } from './generateType'
* @param config
*/
export function request(config: AxiosRequestConfig) {
return new Promise<AxiosResponse>((resolve, reject) => {
const adapterConfig: AxiosAdapterRequestConfig = {
...(config as AxiosAdapterRequestConfig),
type: generateType(config),
url: transformURL(config),
method: config.method!.toUpperCase() as AxiosAdapterRequestMethod,
success,
fail,
}
return new Promise<AxiosResponse>((resolve, reject) => {
const adapterConfig: AxiosAdapterRequestConfig = {
...(config as AxiosAdapterRequestConfig),
type: generateType(config),
url: transformURL(config),
method: config.method!.toUpperCase() as AxiosAdapterRequestMethod,
success,
fail,
};
let adapterTask: AxiosAdapterPlatformTask
try {
adapterTask = config.adapter!(adapterConfig)
} catch (err) {
fail({
status: 400,
statusText: 'Bad Adapter',
})
let adapterTask: AxiosAdapterPlatformTask;
try {
adapterTask = config.adapter!(adapterConfig);
} catch (err) {
fail({
status: 400,
statusText: 'Bad Adapter',
});
console.error(err)
}
console.error(err);
}
function success(baseResponse: AxiosAdapterResponse): void {
const response = baseResponse as AxiosResponse
response.status = response.status ?? 200
response.statusText = response.statusText ?? 'OK'
response.headers = response.headers ?? {}
response.config = config
response.request = adapterTask
function success(rawResponse: AxiosAdapterResponse): void {
const response = rawResponse as AxiosResponse;
response.status ||= 200;
response.statusText ||= getHttpStatusText(response.status);
response.headers ||= {};
response.config = config;
response.request = adapterTask;
const { validateStatus } = config
if (!isFunction(validateStatus) || validateStatus(response.status)) {
resolve(response)
} else {
catchError('validate status error', response)
}
}
const { validateStatus } = config;
if (!isFunction(validateStatus) || validateStatus(response.status)) {
resolve(response);
} else {
catchError('validate status error', response);
}
}
function fail(baseResponseError: AxiosAdapterResponseError): void {
const responseError = baseResponseError as AxiosResponseError
responseError.isFail = true
responseError.status = responseError.status ?? 400
responseError.statusText = responseError.statusText ?? 'Fail'
responseError.headers = responseError.headers ?? {}
responseError.config = config
responseError.request = adapterTask
function fail(rawResponseError: AxiosAdapterResponseError): void {
const responseError = rawResponseError as AxiosResponseError;
responseError.isFail = true;
responseError.status ||= 400;
responseError.statusText ||= getHttpStatusText(responseError.status);
responseError.headers ||= {};
responseError.config = config;
responseError.request = adapterTask;
catchError('request fail', responseError)
}
catchError('request fail', responseError);
}
function catchError(
message: string,
errorResponse: AxiosErrorResponse,
): void {
reject(createError(message, config, errorResponse, adapterTask))
}
function catchError(
message: string,
errorResponse: AxiosErrorResponse,
): void {
reject(createError(message, config, errorResponse, adapterTask));
}
if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate)
}
if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate);
}
const { cancelToken } = config
if (isCancelToken(cancelToken)) {
cancelToken.onCancel((reason) => {
if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate)
const { cancelToken } = config;
if (isCancelToken(cancelToken)) {
cancelToken.onCancel((reason) => {
if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate);
adapterTask?.abort?.()
}
if (isFunction(adapterTask.abort)) {
adapterTask.abort();
}
}
reject(reason)
})
}
})
reject(reason);
});
}
});
}
function tryToggleProgressUpdate(
config: AxiosAdapterRequestConfig,
progress?: (cb: (event: AnyObject) => void) => void,
config: AxiosAdapterRequestConfig,
toggle?: (cb: (event: AnyObject) => void) => void,
) {
const { type, onUploadProgress, onDownloadProgress } = config
if (isFunction(progress)) {
switch (type) {
case 'upload':
if (isFunction(onUploadProgress)) {
progress(onUploadProgress)
}
break
case 'download':
if (isFunction(onDownloadProgress)) {
progress(onDownloadProgress)
}
break
}
}
if (isFunction(toggle)) {
const { type, onUploadProgress, onDownloadProgress } = config;
switch (type) {
case 'upload':
if (isFunction(onUploadProgress)) {
toggle(onUploadProgress);
}
break;
case 'download':
if (isFunction(onDownloadProgress)) {
toggle(onDownloadProgress);
}
break;
}
}
}

View File

@ -1,4 +1,4 @@
import { isArray, isFunction } from '../helpers/isTypes';
import { isArray, isFunction } from '../helpers/types';
export interface AxiosTransformCallback<TData = unknown> {
(

View File

@ -1 +1 @@
export const version = '2.4.1'
export const version = '2.7.2';

View File

@ -200,6 +200,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(`
{
"filePath": undefined,
"fileSize": undefined,
"tempFilePath": "/path/temp/file",
}
`);
@ -212,6 +213,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(`
{
"filePath": undefined,
"fileSize": undefined,
"tempFilePath": "/path/temp/file",
}
`);
@ -226,6 +228,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(`
{
"filePath": "/user/path",
"fileSize": undefined,
"tempFilePath": "/path/temp/file",
}
`);
@ -240,6 +243,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(`
{
"filePath": "/user/path",
"fileSize": undefined,
"tempFilePath": "/path/temp/file",
}
`);
@ -323,4 +327,33 @@ describe('src/adapter/createAdapter.ts', () => {
createAdapter(p2)(c2);
createAdapter(p3)(c3);
});
test('响应数据应该进行JSON.parse', async () => {
const a = createAdapter({
request: vi.fn(),
upload: (options) => {
options.success({
data: '{"id":1}',
});
},
download: vi.fn(),
});
a({
type: 'upload',
url: 'test',
method: 'POST',
dataType: 'json',
responseType: 'text',
data: {},
success(res) {
expect(res.data).toBeTypeOf('object');
// @ts-ignore
expect(res.data.id).toBe(1);
},
fail() {
//
},
});
});
});

View File

@ -2,7 +2,6 @@ import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest';
import { getDefaultAdapter } from '@/adpater/getDefaultAdapter';
const platforms = [
'uni',
'wx',
'my',
'swan',

View File

@ -27,7 +27,6 @@ describe('src/axios.ts', () => {
});
expect(instance.interceptors).toBeTypeOf('object');
expect(instance.getUri).toBeTypeOf('function');
expect(instance.fork).toBeTypeOf('function');
expect(instance.request).toBeTypeOf('function');
eachMethods((k) => {

View File

@ -19,7 +19,6 @@ describe('src/axios.ts', () => {
expect(axios.create).toBeTypeOf('function');
expect(axios.extend).toBeTypeOf('function');
expect(axios.use).toBeTypeOf('function');
expect(axios.fork).toBeTypeOf('function');
expect(axios.request).toBeTypeOf('function');
});

View File

@ -12,7 +12,6 @@ describe('src/core/createInstance.ts', () => {
expect(i.getUri).toBeTypeOf('function');
expect(i.create).toBeTypeOf('function');
expect(i.extend).toBeTypeOf('function');
expect(i.fork).toBeTypeOf('function');
expect(i.use).toBeTypeOf('function');
expect(i.request).toBeTypeOf('function');

View File

@ -127,6 +127,25 @@ describe('src/core/mergeConfig.ts', () => {
expect(mergeConfig(c1 as any, c2 as any)).toEqual({});
});
test('深度合并应该返回新的对象', () => {
const c1 = {
headers: { t: 1 },
params: {},
};
const c2 = {
headers: {},
params: { t: 1 },
};
const c3 = mergeConfig(c1 as any, c2 as any);
expect(c3.headers === c1.headers).toBeFalsy();
expect(c3.params === c1.params).toBeFalsy();
expect(c3.headers === c2.headers).toBeFalsy();
expect(c3.params === c2.params).toBeFalsy();
expect(c3.headers).toEqual(c1.headers);
expect(c3.params).toEqual(c2.params);
});
test('应该优先取 config2', () => {
const c1 = {
adapter: vi.fn(),
@ -138,7 +157,7 @@ describe('src/core/mergeConfig.ts', () => {
errorHandler: vi.fn(),
cancelToken: CancelToken.source().token,
dataType: 'json',
responseType: 'json',
responseType: 'text',
timeout: 1000,
validateStatus: vi.fn(),
onUploadProgress: vi.fn(),
@ -154,7 +173,7 @@ describe('src/core/mergeConfig.ts', () => {
errorHandler: vi.fn(),
cancelToken: CancelToken.source().token,
dataType: 'json',
responseType: 'json',
responseType: 'text',
timeout: 1000,
validateStatus: vi.fn(),
onUploadProgress: vi.fn(),

View File

@ -58,4 +58,12 @@ describe('src/helpers/dynamicURL.ts', () => {
}),
).toBe('http://api.com:8080/0');
});
test('应该支持带参数的链接', () => {
expect(
dynamicURL('http://api.com/test/:id?param=1', {
id: 0,
}),
).toBe('http://api.com/test/0?param=1');
});
});

View File

@ -0,0 +1,16 @@
import { describe, test, expect } from 'vitest';
import { ensureObject } from '@/helpers/ensureObject';
describe('src/helpers/ensureObject.ts', () => {
test('应该始终返回对象', () => {
expect(ensureObject()).toEqual({});
expect(ensureObject(1)).toEqual({});
expect(ensureObject('')).toEqual({});
expect(ensureObject([])).toEqual({});
expect(ensureObject(new Date())).toEqual({});
});
test('应该返回对象参数', () => {
expect(ensureObject({ a: 1 })).toEqual({ a: 1 });
});
});

Some files were not shown because too many files have changed in this diff Show More