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,4 +1,5 @@
{ {
"root": true,
"env": { "env": {
"es2022": true, "es2022": true,
"node": true "node": true
@ -6,10 +7,10 @@
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"], "plugins": ["@typescript-eslint"],
"root": true,
"rules": { "rules": {
"@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0, "@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/ban-ts-comment": 0 "@typescript-eslint/ban-ts-comment": 0,
"no-mixed-spaces-and-tabs": 0
} }
} }

View File

@ -37,13 +37,13 @@ body:
label: 验证 label: 验证
description: 在提交问题之前,请确保您执行以下操作 description: 在提交问题之前,请确保您执行以下操作
options: 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 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 required: true
- label: 阅读[文档](https://axios-miniprogram.com). - label: 阅读[文档](https://axios-miniprogram.com).
required: true required: true
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjx0905/axios-miniprogram/issues)以避免创建重复。 - label: 检查是否还没有报告相同错误的[问题](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)以避免创建重复。
required: true required: true
- label: 确保这是 axios-miniprogram 问题而不是特定于框架的问题。 - label: 确保这是 axios-miniprogram 问题而不是特定于框架的问题。
required: true required: true

View File

@ -17,7 +17,7 @@ body:
id: suggested-solution id: suggested-solution
attributes: attributes:
label: 建议的解决方案 label: 建议的解决方案
description: '在模块 [xy] 中,我们可以提供以下实现......' description: '我们可以提供以下实现......'
validations: validations:
required: true required: true
- type: textarea - type: textarea
@ -36,9 +36,9 @@ body:
label: 验证 label: 验证
description: 在提交问题之前,请确保您执行以下操作 description: 在提交问题之前,请确保您执行以下操作
options: 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 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 required: true
- label: 阅读[文档](https://axios-miniprogram.com). - label: 阅读[文档](https://axios-miniprogram.com).
required: true required: true

View File

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

View File

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

View File

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

View File

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

4
.gitignore vendored
View File

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

View File

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

View File

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

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 ### Bug Fixes
* 配置原始 URL 丢失 ([8b6eed2](https://github.com/zjx0905/axios-miniprogram/commit/8b6eed2d6df5c7aacd181f6fbcfba9eca875178c)) * 修复设置请求 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)
* 配置原始请求方法丢失 ([c107171](https://github.com/zjx0905/axios-miniprogram/commit/c107171eba69a129eddad34861611837a0efac25))
## [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 ### Features
* 请求发送前请求方法转小写 ([0b82403](https://github.com/zjx0905/axios-miniprogram/commit/0b82403c4c630676042ff390b77d5791c4ab0a6e)) * 添加符合 HTTP 规范的 statusText ([#49](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/49)) ([3848fdd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/3848fdd81bf8fb1f5e373ca4e117adb653969acf))
* 允许设置默认请求方法 ([4b02582](https://github.com/zjx0905/axios-miniprogram/commit/4b025821525712d7e6bb68faa9af3cf7d9ad0e0d))
* getUri 支持 baseURL/dynamicURL ([633c920](https://github.com/zjx0905/axios-miniprogram/commit/633c92024718370e24919fcfb44b86b795248c8f))
# [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 ### 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 ### 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 ### Features
* 全局方法 create 改为实例方法 ([a84533a](https://github.com/zjx0905/axios-miniprogram/commit/a84533a09f493e27ba3e567549be5e534271ed22)) * 全局方法 create 改为实例方法 ([a84533a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/a84533a09f493e27ba3e567549be5e534271ed22))
* 添加扩展实例 ([9093e1b](https://github.com/zjx0905/axios-miniprogram/commit/9093e1bdffe5bd75fccfeeeeb0e2b487751c549a)) * 添加扩展实例 ([9093e1b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/9093e1bdffe5bd75fccfeeeeb0e2b487751c549a))
* 添加中间件 ([6263759](https://github.com/zjx0905/axios-miniprogram/commit/6263759ba94b2269082c49a2f2a5e038f6766027)) * 添加中间件 ([6263759](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/6263759ba94b2269082c49a2f2a5e038f6766027))
* 支持复用父级中间件 ([bfc012b](https://github.com/zjx0905/axios-miniprogram/commit/bfc012b4999d717629b997ab908fd411954b0323)) * 支持复用父级中间件 ([bfc012b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/bfc012b4999d717629b997ab908fd411954b0323))
### Reverts ### Reverts
* 取消支持为路径添加中间件 ([1e5809a](https://github.com/zjx0905/axios-miniprogram/commit/1e5809aee3f1653eced0c2ca351c6e3f8616f719)) * 取消支持为路径添加中间件 ([1e5809a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1e5809aee3f1653eced0c2ca351c6e3f8616f719))
### BREAKING CHANGES ### 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 ### 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 ### Bug Fixes
* 控制台没有输出适配器错误 ([258954a](https://github.com/zjx0905/axios-miniprogram/commit/258954afc1c39483ff6b1828c8904c5b284890d2)) * 控制台没有输出适配器错误 ([258954a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/258954afc1c39483ff6b1828c8904c5b284890d2))
* 下载进度/上传进度 类型错误 ([2d691b6](https://github.com/zjx0905/axios-miniprogram/commit/2d691b69cbb2d3e27be3698bf4a4188cf71ccb7e)) * 下载进度/上传进度 类型错误 ([2d691b6](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2d691b69cbb2d3e27be3698bf4a4188cf71ccb7e))
### Features ### 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 ### Bug Fixes
* 错误处理不是每次出错都执行 ([fb4762d](https://github.com/zjx0905/axios-miniprogram/commit/fb4762d01a0d304ce6c291d6487dce1507a985c5)) * 错误处理不是每次出错都执行 ([fb4762d](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/fb4762d01a0d304ce6c291d6487dce1507a985c5))
* data 不支持对象以外的类型 ([4d8ec80](https://github.com/zjx0905/axios-miniprogram/commit/4d8ec80f29b85e3419d1bc5112886a397ee2cc48)) * data 不支持对象以外的类型 ([4d8ec80](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4d8ec80f29b85e3419d1bc5112886a397ee2cc48))
### Features ### Features
* 从参数中删除动态地址属性 ([b0eaa04](https://github.com/zjx0905/axios-miniprogram/commit/b0eaa04c66dc82de944769893f62ecd0c4ae76d8)) * 从参数中删除动态地址属性 ([b0eaa04](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b0eaa04c66dc82de944769893f62ecd0c4ae76d8))
* 提供更多可使用的类型 ([0dc58a4](https://github.com/zjx0905/axios-miniprogram/commit/0dc58a4b0cdd5d36c1b16f13697d8180952cb093)) * 提供更多可使用的类型 ([0dc58a4](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0dc58a4b0cdd5d36c1b16f13697d8180952cb093))
* 支持具名导入工具函数 ([d714ed2](https://github.com/zjx0905/axios-miniprogram/commit/d714ed23c0f3b8ea3abecfb042c67bcf9adb29a7)) * 支持具名导入工具函数 ([d714ed2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/d714ed23c0f3b8ea3abecfb042c67bcf9adb29a7))
* 支持清空拦截器 ([cbcc43a](https://github.com/zjx0905/axios-miniprogram/commit/cbcc43ad77f0e79223e524aa6bb4502ee4b989c9)) * 支持清空拦截器 ([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 ### 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 ### Features
* 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjx0905/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77)) * 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77))
* 支持 HTTP PATCH 请求 ([22bcefc](https://github.com/zjx0905/axios-miniprogram/commit/22bcefcb97e50400403b131d307c97eb4cbb6071)) * 支持 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 ### Bug Fixes
* 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjx0905/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136)) * 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136))
* 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjx0905/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8)) * 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8))
### Features ### Features
* 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjx0905/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777)) * 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777))
* 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjx0905/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9)) * 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9))
* 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjx0905/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7)) * 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7))
* 支持深度合并 params & data ([22f65cf](https://github.com/zjx0905/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f)) * 支持深度合并 params & data ([22f65cf](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f))
* fileName 替换为 name ([69044f3](https://github.com/zjx0905/axios-miniprogram/commit/69044f35833d8d42a5f0c12b01687298c08f589b)) * 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 ### Bug Fixes
* 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjx0905/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a)) * 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a))
### Features ### Features
* 添加新的 API isAxiosError ([61337a9](https://github.com/zjx0905/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842)) * 添加新的 API isAxiosError ([61337a9](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842))
* 优化 defaults ([2793dd8](https://github.com/zjx0905/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf)) * 优化 defaults ([2793dd8](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf))
### BREAKING CHANGES ### 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 ### 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 ### Bug Fixes
* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjx0905/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84)) * 清理 url 前面多余的斜线 ([666a942](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))
### Features ### Features
* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjx0905/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a)) * 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjx0905/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjx0905/axios-miniprogram/issues/38) * 支持合并自定义配置 ([4409a57](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjx0905/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e)) * 支持京东小程序 ([0d1d21f](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjx0905/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1)) * 支持自定义配置 ([b15b31e](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))
### BREAKING CHANGES ### BREAKING CHANGES

View File

@ -34,7 +34,7 @@ pnpm cz
脚本列表 脚本列表
- `pnpm build` 打包源代码 - `pnpm build` 打包源代码
- `pnpm watch` 监听文件变更并运行 `build` - `pnpm dev` 监听文件变更并运行 `build`
- `pnpm test` 单元测试 - `pnpm test` 单元测试
- `pnpm test:watch` 监听文件变更并运行 `test` - `pnpm test:watch` 监听文件变更并运行 `test`
- `pnpm test:cov` 运行 `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) 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal 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;"> <p style="text-align: center;" align="center">
<a href="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml"> <a style="display: inline-block;margin-left: 5px;" href="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci"> <img src="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci"/>
</a> </a>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram"> <a style="display: inline-block;margin-left: 5px;" href="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram" >
<img src="https://img.shields.io/npm/v/axios-miniprogram" alt="npm"> <img src="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
</a> </a>
<a style="margin-left:5px;" href="https://codecov.io/gh/zjx0905/axios-miniprogram" > <a style="display: inline-block;margin-left: 5px;" href="https://opensource.org/licenses/MIT">
<img src="https://codecov.io/gh/zjx0905/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/> <img src="https://img.shields.io/github/license/zjxxxxxxxxx/axios-miniprogram" alt="license"/>
</a> </a>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram"> <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"> <img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size"/>
</a> </a>
<a style="margin-left:5px;" href="https://opensource.org/licenses/MIT"> <a style="display: inline-block;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/github/license/zjx0905/axios-miniprogram" alt="license"> <img alt="npm" src="https://img.shields.io/npm/dt/axios-miniprogram"/>
</a> </a>
</p> </p>
[中文文档](https://axios-miniprogram.com) <p style="text-align: center;" align="center">
<a href='https://axios-miniprogram.com'>中文文档</a>
</p>
## axios-miniprogram 是什么? ## axios-miniprogram 是什么?
@ -51,17 +53,28 @@ axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库
- [飞书小程序](https://open.feishu.cn/document/uYjL24iN/uMjNzUjLzYzM14yM2MTN?from=axios-miniprogram) - [飞书小程序](https://open.feishu.cn/document/uYjL24iN/uMjNzUjLzYzM14yM2MTN?from=axios-miniprogram)
- [快手小程序](https://mp.kuaishou.com/docs/introduction/quickStart.html?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) - [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 进行了封装,并没有使用什么黑魔法。理论上来讲,框架支持的平台,该库也必然支持。 答:该请求库只是对框架提供的请求 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: '/basics/request', activeMatch: '/basics/' },
{ {
text: '进阶', text: '进阶',
link: '/advanced/request-interceptor', link: '/advanced/middleware',
activeMatch: '/advanced/', activeMatch: '/advanced/',
}, },
], ],
@ -29,15 +29,18 @@ export default defineConfig({
sidebar: sidebar(), sidebar: sidebar(),
socialLinks: [ socialLinks: [
{ icon: 'github', link: 'https://github.com/zjx0905/axios-miniprogram' }, {
icon: 'github',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram',
},
], ],
editLink: { editLink: {
pattern: ({ relativePath }) => { pattern: ({ relativePath }) => {
if (relativePath.endsWith('/intro.md')) { 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 上编辑此页面', text: '在 GitHub 上编辑此页面',
}, },
@ -55,9 +58,9 @@ export default defineConfig({
}, },
footer: { footer: {
message: 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:
'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/instance' },
{ text: '扩展实例', link: '/advanced/extend' }, { text: '扩展实例', link: '/advanced/extend' },
{ text: '平台适配器', link: '/advanced/adapter' }, { text: '平台适配器', link: '/advanced/adapter' },
{ text: '派生领域(即将废弃)', link: '/advanced/fork' },
], ],
collapsed: false, collapsed: false,
}, },
@ -146,11 +148,11 @@ function sidebar() {
items: [ items: [
{ {
text: '行为准则', 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: '贡献指南', 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); margin-top: var(--vp-nav-height);
padding-top: 40px !important; padding-top: 40px !important;
height: calc(100% - var(--vp-nav-height)); 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; transition: transform 0.3s cubic-bezier(0.19, 1, 0.22, 1) !important;
} }
@ -149,11 +148,6 @@
} }
.vp-code-group .tabs { .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); border-color: var(--vp-c-gutter);
} }
@ -211,7 +205,6 @@
.language-bash, .language-bash,
.language-ts { .language-ts {
border-radius: 6px; border-radius: 6px;
border: 1px solid var(--vp-c-gutter);
} }
.prev-next { .prev-next {

View File

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

View File

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

View File

@ -20,7 +20,7 @@ import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com'; axios.defaults.baseURL = 'https://api.com';
// 相对地址会进行组合 // 相对地址会进行组合
// baseURL 最终结果为 https://api.com/uesr // baseURL 最终结果为 https://api.com/user
const instance = axios.extend({ const instance = axios.extend({
baseURL: 'user', baseURL: 'user',
headers: { 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', baseURL: 'user',
}); });
// 请求的服务端地址 https://api2.com/uesr // 请求的服务端地址 https://api2.com/user
child('/'); child('/');
``` ```

View File

@ -11,9 +11,10 @@ title: 中间件
## 前言 ## 前言
如果您了解或者使用过[koa](https://github.com/koajs/koa),相信您一定十分了解什么是洋葱模型,中间件该怎么写。 如果您了解或者使用过[koa](https://github.com/koajs/koa),相信您一定十分了解什么是洋葱模型,中间件该怎么写。
中间件是一个异步函数,接收 `context``next` 两个参数。 中间件是一个异步函数,接收 `context``next` 两个参数。
`context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其成部分。 `context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其成部分。
- `context.req`:请求配置。 - `context.req`:请求配置。
- `context.res`:请求完成后服务端返回的响应体,它的初始值是 `null`,请求完成之后才能对其进行操作。 - `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'); 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 ```ts
{ {
@ -174,4 +174,4 @@ axios.interceptors.response.use((response) => {
2. `headers`、`params` 会分别进行深度合并。 2. `headers`、`params` 会分别进行深度合并。
3. 其余属性则会优先从 `config` 取值。 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 { const {
// 临时文件路径 (本地路径)。没传入 filePath 指定文件存储路径时会返回,下载后的文件会存储到一个临时文件 // 临时文件路径 (本地路径)。没传入 filePath 指定文件存储路径时会返回,下载后的文件会存储到一个临时文件
tempFilePath, tempFilePath,
} = response; } = response.data;
}) })
.catch((error) => { .catch((error) => {
// 失败之后做些什么 // 失败之后做些什么
@ -50,7 +50,7 @@ axios('https://api.com/test', {
const { const {
// 指定文件下载后存储的路径 (本地路径) // 指定文件下载后存储的路径 (本地路径)
filePath, filePath,
} = response; } = response.data;
}) })
.catch((error) => { .catch((error) => {
// 失败之后做些什么 // 失败之后做些什么
@ -86,7 +86,7 @@ axios('https://api.com/test', {
const { const {
// 指定文件下载后存储的路径 (本地路径) // 指定文件下载后存储的路径 (本地路径)
filePath, filePath,
} = response; } = response.data;
}) })
.catch((error) => { .catch((error) => {
// 失败之后做些什么 // 失败之后做些什么

View File

@ -9,20 +9,20 @@ title: 开始
:::: code-group :::: code-group
```bash [NPM] ```bash [NPM]
$ npm install -D axios-miniprogram $ npm install axios-miniprogram
``` ```
```bash [YARN] ```bash [YARN]
$ yarn add -D axios-miniprogram $ yarn add axios-miniprogram
``` ```
```bash [PNPM] ```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 wx: any;
declare const my: any; declare const my: any;
declare const swan: any; declare const swan: any;
@ -8,3 +7,4 @@ declare const qh: any;
declare const ks: any; declare const ks: any;
declare const dd: any; declare const dd: any;
declare const jd: any; declare const jd: any;
declare const xhs: any;

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
import { writeFileSync } from 'node:fs'; import { writeFileSync } from 'node:fs';
import semver from 'semver'; import semver, { ReleaseType } from 'semver';
import enquirer from 'enquirer'; import enquirer from 'enquirer';
import consola from 'consola'; import consola from 'consola';
import { exec, pkgPath, getPkgJSON, resolve } from './utils'; import { exec, pkgPath, getPkgJSON, resolve } from './utils';
@ -27,10 +27,10 @@ async function main() {
exec(`git tag -a v${version} -m "v${version}"`); exec(`git tag -a v${version} -m "v${version}"`);
consola.info('Git push'); consola.info('Git push');
exec('git push'); exec('git push -f');
consola.info('Git push tag'); consola.info('Git push tag');
exec(`git push origin v${version}`); exec(`git push -f origin v${version}`);
} }
function checkBranch() { function checkBranch() {
@ -103,7 +103,9 @@ function createReleases() {
]; ];
const releases: string[] = []; const releases: string[] = [];
for (const [type, preid] of types) { 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; 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( export function mockResponse(
status = 200, status = 200,
statusText = 'OK',
headers: AnyObject = {}, headers: AnyObject = {},
data: AnyObject = {}, data: AnyObject = {},
) { ) {
return { return {
status, status,
statusText,
headers, headers,
data, data,
}; };
@ -72,13 +70,13 @@ function mockAdapterBase(
if (!canceled) { if (!canceled) {
switch (type) { switch (type) {
case 'success': case 'success':
config.success(mockResponse(200, 'OK', headers, data)); config.success(mockResponse(200, headers, data));
break; break;
case 'error': case 'error':
config.success(mockResponse(500, 'ERROR', headers, data)); config.success(mockResponse(500, headers, data));
break; break;
case 'fail': case 'fail':
config.fail(mockResponse(400, 'FAIL', headers, data)); config.fail(mockResponse(400, headers, data));
break; break;
} }

View File

@ -1,39 +1,40 @@
import { isPromise } from 'node:util/types' import { isPromise } from 'node:util/types';
import path from 'node:path' import path from 'node:path';
import { createRequire } from 'node:module' import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url';
import { ExecSyncOptions, execSync } from 'node:child_process' import { ExecSyncOptions, execSync } from 'node:child_process';
import consola from 'consola' import consola from 'consola';
export const __dirname = fileURLToPath(new URL('../', import.meta.url)) export const __dirname = fileURLToPath(new URL('../', import.meta.url));
export const require = createRequire(import.meta.url) export const require = createRequire(import.meta.url);
export const pkgPath = path.resolve(__dirname, 'package.json') export const pkgPath = path.resolve(__dirname, 'package.json');
export const distPath = path.resolve(__dirname, 'dist') 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 = {}) => export const exec = (command: string, options: ExecSyncOptions = {}) =>
execSync(command, { execSync(command, {
stdio: 'inherit', stdio: 'inherit',
encoding: 'utf-8', encoding: 'utf-8',
...options, ...options,
}) });
export const getPkgJSON = () => require(pkgPath) export const getPkgJSON = () => require(pkgPath);
export function safeExit(run: () => unknown) { export function safeExit(run: () => unknown) {
try { try {
const p = run() const p = run();
if (isPromise(p)) { if (isPromise(p)) {
return p.catch(exit) return p.catch(exit);
} }
} catch { } catch {
exit() exit();
} }
} }
function exit() { function exit() {
consola.error('已退出') consola.error('已退出');
process.exit() 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 { assert } from '../helpers/error';
import { origIgnore } from '../helpers/ignore'; import { ignore, orgIgnore } from '../helpers/ignore';
import { import {
AxiosProgressEvent, AxiosProgressEvent,
AxiosRequestFormData, AxiosRequestFormData,
@ -44,10 +44,6 @@ export interface AxiosAdapterResponse extends AnyObject {
* *
*/ */
status?: number; status?: number;
/**
*
*/
statusText?: string;
/** /**
* *
*/ */
@ -66,10 +62,6 @@ export interface AxiosAdapterResponseError extends AnyObject {
* *
*/ */
status?: number; status?: number;
/**
*
*/
statusText?: string;
/** /**
* *
*/ */
@ -111,11 +103,11 @@ export interface AxiosAdapterRequestConfig extends AnyObject {
/** /**
* *
*/ */
dataType?: 'json' | '其他'; dataType?: string;
/** /**
* *
*/ */
responseType?: 'text' | 'arraybuffer'; responseType?: string;
/** /**
* 60000 * 60000
*/ */
@ -170,11 +162,11 @@ export interface AxiosAdapterUploadOptions
extends AxiosAdapterBaseOptions, extends AxiosAdapterBaseOptions,
AxiosRequestFormData { 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; fileName: string;
/** /**
* | * |
*/ */
fileType?: 'image' | 'video' | 'audie'; fileType?: 'image' | 'video' | 'audie';
/** /**
@ -269,82 +261,134 @@ export function createAdapter(platform: AxiosAdapterPlatform) {
function transformOptions( function transformOptions(
config: AxiosAdapterRequestConfig, config: AxiosAdapterRequestConfig,
): AxiosAdapterBaseOptions { ): AxiosAdapterBaseOptions {
const { success, fail } = config;
return { return {
...config, ...config,
header: config.headers, header: config.headers,
success(response: AxiosAdapterResponse) { success(rawRes: AxiosAdapterResponse) {
transformResponse(response); const response = transformResponse(rawRes) as AxiosAdapterResponse;
config.success(response); success(response);
},
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,
}, },
fail(responseError: AxiosAdapterResponseError) {
responseError.data = {
errMsg: responseError.errMsg,
errno: responseError.errno,
}; };
transformResponse(responseError); fail(responseError);
config.fail(responseError);
}, },
}; };
} }
function transformResponse( function transformResponse(
response: AxiosAdapterResponse | AxiosAdapterResponseError, rawRes: AxiosAdapterResponse | AxiosAdapterResponseError,
) { ) {
response.status = response.status ?? response.statusCode; return {
response.headers = response.headers ?? response.header; ...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( function processRequest(
request: AxiosAdapterRequest, request: AxiosAdapterRequest,
baseOptions: AxiosAdapterBaseOptions, rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask { ): AxiosAdapterPlatformTask {
return request(baseOptions); return request(rawOpts);
}
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);
} }
function processDownload( function processDownload(
download: AxiosAdapterDownload, download: AxiosAdapterDownload,
baseOptions: AxiosAdapterBaseOptions, rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask { ): AxiosAdapterPlatformTask {
const options = baseOptions as AxiosAdapterDownloadOptions; const options = rawOpts as AxiosAdapterDownloadOptions;
const { params, success } = options; const { params, success } = options;
options.filePath = params?.filePath; options.filePath = params?.filePath;
options.success = (response) => { options.success = (rawRes) => {
response.data = { const response = {
filePath: response.filePath, ...ignore(rawRes, 'tempFilePath', 'apFilePath', 'filePath', 'fileSize'),
data: {
filePath: rawRes.filePath,
tempFilePath: tempFilePath:
response.tempFilePath || rawRes.tempFilePath ??
// response.apFilePath 为支付宝小程序基础库小于 2.7.23 的特有属性。 // 支付宝
response.apFilePath, rawRes.apFilePath,
fileSize:
// 飞书
rawRes.fileSize,
},
}; };
origIgnore(response, ['tempFilePath', 'apFilePath', 'filePath']);
success(response); success(response);
}; };
origIgnore(options, ['params']); orgIgnore(options, ['params']);
return download(options); 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; 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'; import { AxiosAdapterPlatform, createAdapter } from './createAdapter';
/** /**
@ -6,48 +6,64 @@ import { AxiosAdapterPlatform, createAdapter } from './createAdapter';
*/ */
export function getDefaultAdapter() { export function getDefaultAdapter() {
const platform = revisePlatformApiNames(getPlatform()); const platform = revisePlatformApiNames(getPlatform());
if (!isPlatform(platform)) { if (isPlatform(platform)) {
return; return createAdapter(platform);
}
} }
function getPlatform() { function getPlatform() {
const undef = 'undefined'; const undef = 'undefined';
if (typeof uni !== undef) { // 微信小程序
return { if (typeof wx !== undef) {
request: uni.request,
downloadFile: uni.downloadFile,
uploadFile: uni.uploadFile,
};
} else if (typeof wx !== undef) {
return wx; return wx;
} else if (typeof my !== undef) { }
// 支付宝小程序
else if (typeof my !== undef) {
return my; return my;
} else if (typeof swan !== undef) { }
// 百度小程序
else if (typeof swan !== undef) {
return swan; return swan;
} else if (typeof tt !== undef) { }
// 抖音小程序 | 飞书小程序
else if (typeof tt !== undef) {
return tt; return tt;
} else if (typeof qq !== undef) { }
// QQ 小程序
else if (typeof qq !== undef) {
return qq; return qq;
} else if (typeof qh !== undef) { }
// 360 小程序
else if (typeof qh !== undef) {
return qh; return qh;
} else if (typeof ks !== undef) { }
// 快手小程序
else if (typeof ks !== undef) {
return ks; return ks;
} else if (typeof dd !== undef) { }
// 钉钉小程序
else if (typeof dd !== undef) {
return dd; return dd;
} else if (typeof jd !== undef) { }
// 京东小程序
else if (typeof jd !== undef) {
return jd; return jd;
} }
// 小红书小程序
else if (typeof xhs !== undef) {
return xhs;
}
} }
function revisePlatformApiNames(platform?: AnyObject) { function revisePlatformApiNames(platform?: AnyObject) {
return ( if (platform) {
platform && { return {
request: platform.request ?? platform.httpRequest, request: platform.request ?? platform.httpRequest,
upload: platform.upload ?? platform.uploadFile, upload: platform.upload ?? platform.uploadFile,
download: platform.download ?? platform.downloadFile, download: platform.download ?? platform.downloadFile,
};
} }
);
} }
function isPlatform(value: any): value is AxiosAdapterPlatform { function isPlatform(value: any): value is AxiosAdapterPlatform {
@ -58,6 +74,3 @@ export function getDefaultAdapter() {
isFunction(value.download) isFunction(value.download)
); );
} }
return createAdapter(platform);
}

View File

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

View File

@ -29,20 +29,26 @@ export interface InterceptorExecutor<T = unknown> {
*/ */
export default class InterceptorManager<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() { get size() {
return this.#interceptors.size; return this.interceptors.size;
} }
/** /**
@ -56,12 +62,12 @@ export default class InterceptorManager<T = unknown> {
resolved: InterceptorResolved<T>, resolved: InterceptorResolved<T>,
rejected?: InterceptorRejected<T>, rejected?: InterceptorRejected<T>,
): number { ): number {
this.#interceptors.set(++this.#id, { this.interceptors.set(++this.id, {
resolved, resolved,
rejected, rejected,
}); });
return this.#id; return this.id;
} }
/** /**
@ -70,22 +76,24 @@ export default class InterceptorManager<T = unknown> {
* @param id * @param id
*/ */
eject(id: number): boolean { eject(id: number): boolean {
return this.#interceptors.delete(id); return this.interceptors.delete(id);
} }
/** /**
* *
*/ */
clear() { clear() {
this.#interceptors.clear(); this.interceptors.clear();
} }
/** /**
* @internal
*
* *
* *
* @param executor * @param executor
*/ */
forEach(executor: InterceptorExecutor<T>): void { 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 { assert } from '../helpers/error';
import { isFunction } from '../helpers/isTypes'; import { isFunction } from '../helpers/types';
import { AxiosRequestConfig, AxiosResponse } from './Axios'; import { AxiosRequestConfig, AxiosResponse } from './Axios';
export interface MiddlewareNext { export interface MiddlewareNext {
@ -34,22 +34,23 @@ export interface MiddlewareCallback {
*/ */
export default class MiddlewareManager { export default class MiddlewareManager {
/** /**
* @internal
*
* *
*/ */
#middlewares: MiddlewareCallback[] = []; private middlewares: MiddlewareCallback[] = [];
/** /**
* *
*
* @param middleware
*/ */
use = (middleware: MiddlewareCallback) => { use(middleware: MiddlewareCallback) {
assert(isFunction(middleware), 'middleware 不是一个 function'); assert(isFunction(middleware), 'middleware 不是一个 function');
this.#middlewares.push(middleware); this.middlewares.push(middleware);
return this; }
};
/** /**
* @internal
*
* *
*/ */
createContext(config: AxiosRequestConfig): MiddlewareContext { createContext(config: AxiosRequestConfig): MiddlewareContext {
@ -60,13 +61,15 @@ export default class MiddlewareManager {
} }
/** /**
* * @internal
*
*
* *
* @param ctx * @param ctx
* @param respond * @param respond
*/ */
run(ctx: MiddlewareContext, respond: MiddlewareCallback) { run(ctx: MiddlewareContext, respond: MiddlewareCallback) {
const middlewares = [...this.#middlewares, respond]; const middlewares = [...this.middlewares, respond];
async function next() { async function next() {
await middlewares.shift()!(ctx, next); await middlewares.shift()!(ctx, next);
} }
@ -74,7 +77,9 @@ export default class MiddlewareManager {
} }
/** /**
* * @internal
*
*
* *
* @param enhancer * @param enhancer
*/ */

View File

@ -1,3 +1,4 @@
import { dynamicURL } from '../helpers/dynamicURL';
import { combineURL } from '../helpers/combineURL'; import { combineURL } from '../helpers/combineURL';
import { transformURL } from '../helpers/transformURL'; import { transformURL } from '../helpers/transformURL';
import Axios, { import Axios, {
@ -43,21 +44,17 @@ export interface AxiosInstance extends AxiosRequest, Axios {
* @param config * @param config
*/ */
extend(config: AxiosRequestConfig): AxiosInstance; extend(config: AxiosRequestConfig): AxiosInstance;
/**
*
*
* @param config
*
* @deprecated 使 extend fork
*/
fork(config: AxiosRequestConfig): AxiosInstance;
} }
export function createInstance(defaults: AxiosRequestConfig, parent?: Axios) { export function createInstance(
const context = new Axios(defaults, parent); defaults: AxiosRequestConfig,
parentContext?: Axios,
) {
const context = new Axios(defaults, parentContext);
const instance = context.request as AxiosInstance; const instance = context.request as AxiosInstance;
instance.getUri = function getUri(config) { instance.getUri = function getUri(config) {
config.url = dynamicURL(config.url!, config.params, config.data);
return transformURL(mergeConfig(defaults, config)); return transformURL(mergeConfig(defaults, config));
}; };
instance.create = function create(config) { instance.create = function create(config) {
@ -67,7 +64,6 @@ export function createInstance(defaults: AxiosRequestConfig, parent?: Axios) {
config.baseURL = combineURL(defaults.baseURL, config.baseURL); config.baseURL = combineURL(defaults.baseURL, config.baseURL);
return createInstance(mergeConfig(defaults, config), context); return createInstance(mergeConfig(defaults, config), context);
}; };
instance.fork = instance.extend;
Object.assign(instance, context); Object.assign(instance, context);
Object.setPrototypeOf(instance, Axios.prototype); 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 { deepMerge } from '../helpers/deepMerge';
import { AxiosRequestConfig } from './Axios'; import { AxiosRequestConfig } from './Axios';
@ -39,12 +39,10 @@ export function mergeConfig(
} }
// 深度合并 config1 和 config2 中的对象 // 深度合并 config1 和 config2 中的对象
else if (deepMergeConfigMap[key]) { else if (deepMergeConfigMap[key]) {
if (isPlainObject(val1) && isPlainObject(val2)) { if (isPlainObject(val1)) {
config[key] = deepMerge(val1, val2); config[key] = deepMerge(val1, isPlainObject(val2) ? val2 : {});
} else if (isPlainObject(val2)) { } else if (isPlainObject(val2)) {
config[key] = val2; config[key] = deepMerge(val2, {});
} else if (isPlainObject(val1)) {
config[key] = val1;
} }
} }
// 优先从 config2 中取值,如果没有值就从 config1 中取值 // 优先从 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( export function buildURL(
url = '', 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 { export function deepMerge<T extends AnyObject>(...objs: (T | undefined)[]): T {
const result: AnyObject = {}; 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( export function dynamicURL(
url: string, url: string,
params: AnyObject = {}, params: AnyObject = {},
data: AnyObject = {}, data: AxiosRequestData = {},
) { ) {
const dataObject = ensureObject(data);
return url.replace(dynamicRE, (_, $2) => { return url.replace(dynamicRE, (_, $2) => {
const value = params[$2] ?? data[$2]; const value = params[$2] ?? dataObject[$2];
if ($2 in params) { if ($2 in params) {
delete params[$2]; 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[] ...keys: K[]
): Omit<T, K> { ): Omit<T, K> {
const res = { ...obj }; const res = { ...obj };
origIgnore(res, keys); orgIgnore(res, keys);
return res; return res;
} }
@ -19,7 +19,7 @@ export function ignore<T extends AnyObject, K extends keyof T>(
* @param obj * @param obj
* @param keys * @param keys
*/ */
export function origIgnore(obj: AnyObject, keys: PropertyKey[]) { export function orgIgnore(obj: AnyObject, keys: PropertyKey[]) {
for (const key of keys) { for (const key of keys) {
delete obj[key as string | number]; delete obj[key as string | number];
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
import { isArray, isFunction } from '../helpers/isTypes'; import { isArray, isFunction } from '../helpers/types';
export interface AxiosTransformCallback<TData = unknown> { 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(` expect(response.data).toMatchInlineSnapshot(`
{ {
"filePath": undefined, "filePath": undefined,
"fileSize": undefined,
"tempFilePath": "/path/temp/file", "tempFilePath": "/path/temp/file",
} }
`); `);
@ -212,6 +213,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(` expect(response.data).toMatchInlineSnapshot(`
{ {
"filePath": undefined, "filePath": undefined,
"fileSize": undefined,
"tempFilePath": "/path/temp/file", "tempFilePath": "/path/temp/file",
} }
`); `);
@ -226,6 +228,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(` expect(response.data).toMatchInlineSnapshot(`
{ {
"filePath": "/user/path", "filePath": "/user/path",
"fileSize": undefined,
"tempFilePath": "/path/temp/file", "tempFilePath": "/path/temp/file",
} }
`); `);
@ -240,6 +243,7 @@ describe('src/adapter/createAdapter.ts', () => {
expect(response.data).toMatchInlineSnapshot(` expect(response.data).toMatchInlineSnapshot(`
{ {
"filePath": "/user/path", "filePath": "/user/path",
"fileSize": undefined,
"tempFilePath": "/path/temp/file", "tempFilePath": "/path/temp/file",
} }
`); `);
@ -323,4 +327,33 @@ describe('src/adapter/createAdapter.ts', () => {
createAdapter(p2)(c2); createAdapter(p2)(c2);
createAdapter(p3)(c3); 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'; import { getDefaultAdapter } from '@/adpater/getDefaultAdapter';
const platforms = [ const platforms = [
'uni',
'wx', 'wx',
'my', 'my',
'swan', 'swan',

View File

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

View File

@ -19,7 +19,6 @@ describe('src/axios.ts', () => {
expect(axios.create).toBeTypeOf('function'); expect(axios.create).toBeTypeOf('function');
expect(axios.extend).toBeTypeOf('function'); expect(axios.extend).toBeTypeOf('function');
expect(axios.use).toBeTypeOf('function'); expect(axios.use).toBeTypeOf('function');
expect(axios.fork).toBeTypeOf('function');
expect(axios.request).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.getUri).toBeTypeOf('function');
expect(i.create).toBeTypeOf('function'); expect(i.create).toBeTypeOf('function');
expect(i.extend).toBeTypeOf('function'); expect(i.extend).toBeTypeOf('function');
expect(i.fork).toBeTypeOf('function');
expect(i.use).toBeTypeOf('function'); expect(i.use).toBeTypeOf('function');
expect(i.request).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({}); 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', () => { test('应该优先取 config2', () => {
const c1 = { const c1 = {
adapter: vi.fn(), adapter: vi.fn(),
@ -138,7 +157,7 @@ describe('src/core/mergeConfig.ts', () => {
errorHandler: vi.fn(), errorHandler: vi.fn(),
cancelToken: CancelToken.source().token, cancelToken: CancelToken.source().token,
dataType: 'json', dataType: 'json',
responseType: 'json', responseType: 'text',
timeout: 1000, timeout: 1000,
validateStatus: vi.fn(), validateStatus: vi.fn(),
onUploadProgress: vi.fn(), onUploadProgress: vi.fn(),
@ -154,7 +173,7 @@ describe('src/core/mergeConfig.ts', () => {
errorHandler: vi.fn(), errorHandler: vi.fn(),
cancelToken: CancelToken.source().token, cancelToken: CancelToken.source().token,
dataType: 'json', dataType: 'json',
responseType: 'json', responseType: 'text',
timeout: 1000, timeout: 1000,
validateStatus: vi.fn(), validateStatus: vi.fn(),
onUploadProgress: vi.fn(), onUploadProgress: vi.fn(),

View File

@ -58,4 +58,12 @@ describe('src/helpers/dynamicURL.ts', () => {
}), }),
).toBe('http://api.com:8080/0'); ).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