Compare commits

...

136 Commits

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
zjx0905 fa5979b17e chore: release v2.4.1 2023-05-04 11:11:28 +08:00
zjx0905 cea4be518c chore: 修改部分内容 2023-05-04 11:10:07 +08:00
zjx0905 52037b8794 build: 优化包体积 2023-05-04 11:10:07 +08:00
zjx0905 671df397d3 docs: 修正错误处理示例 2023-05-04 11:08:01 +08:00
zjx0905 f23d27024f chore: 一些小的调整 2023-04-27 21:25:47 +08:00
zjx0905 e643f36fe0 chore: 移除 cleanStack 2023-04-27 11:08:24 +08:00
zjx0905 633c920247 feat: getUri 支持 baseURL/dynamicURL 2023-04-27 10:54:27 +08:00
zjx0905 0b82403c4c feat: 请求发送前请求方法转小写 2023-04-27 10:45:58 +08:00
zjx0905 c107171eba fix: 配置原始请求方法丢失 2023-04-27 10:34:36 +08:00
zjx0905 8b6eed2d6d fix: 配置原始 URL 丢失 2023-04-27 10:23:52 +08:00
zjx0905 4b02582152 feat: 允许设置默认请求方法 2023-04-27 09:45:48 +08:00
zjx0905 63f424133e docs: 介绍中间件 2023-04-26 22:57:18 +08:00
zjx0905 3931f230de perf: 优化中间件 2023-04-26 21:03:00 +08:00
zjx0905 f5db1102ce ci: 修改 release 2023-04-26 09:57:28 +08:00
zjx0905 0c562165c9 chore: release v2.4.0 2023-04-25 23:04:44 +08:00
zjx0905 db72446aa1 docs: 介绍扩展实例 2023-04-25 23:02:05 +08:00
zjx0905 1e5809aee3 revert: 取消支持为路径添加中间件 2023-04-25 22:18:08 +08:00
zjx0905 db787a2b5f fix: 丢失末尾自带的斜线
#44
2023-04-25 15:06:19 +08:00
zjx0905 bfc012b499 feat: 支持复用父级中间件 2023-04-25 14:28:28 +08:00
zjx0905 a84533a09f feat: 全局方法 create 改为实例方法 2023-04-25 11:59:50 +08:00
zjx0905 9093e1bdff feat: 添加扩展实例
BREAKING CHANGE :
原派生领域替换为功能更强的扩展实例
2023-04-25 11:54:10 +08:00
zjx0905 6263759ba9 feat: 添加中间件 2023-04-23 23:05:30 +08:00
zjx0905 7bfeba832c chore: release v2.3.2 2023-04-23 14:23:52 +08:00
zjx0905 c0ca9001d2 fix: 适配器请求头丢失
#43
2023-04-23 14:23:06 +08:00
zjx0905 968bbb775e refactor: 拆分模块 2023-04-22 16:12:32 +08:00
zjx0905 5aad9a83ab chore: release v2.3.1 2023-04-21 23:39:33 +08:00
zjx0905 cd65ce4a91 refactor: 新的目录结构 2023-04-21 18:09:32 +08:00
zjx0905 2d691b69cb fix: 下载进度/上传进度 类型错误 2023-04-20 21:49:26 +08:00
zjx0905 1867273460 refactor: 默认值的设置流程移到 request 里 2023-04-20 13:56:17 +08:00
zjx0905 258954afc1 fix: 控制台没有输出适配器错误 2023-04-20 10:57:10 +08:00
zjx0905 d021996c40 docs: 更新 algolia 2023-04-19 22:52:35 +08:00
zjx0905 7c29d2b74f docs: 修改错别字 2023-04-19 21:49:48 +08:00
zjx0905 e3346a866f feat: 添加版本号 2023-04-19 21:36:06 +08:00
zjx0905 5469471cea docs: 介绍转换数据 2023-04-19 12:00:06 +08:00
zjx0905 95567866c8 chore: release v2.3.0 2023-04-18 23:09:51 +08:00
zjx0905 4d8ec80f29 fix: data 不支持对象以外的类型 2023-04-18 23:08:49 +08:00
zjx0905 d714ed23c0 feat: 支持具名导入工具函数 2023-04-18 19:50:40 +08:00
zjx0905 a374647c7d docs: 添加安装建议 2023-04-18 11:23:27 +08:00
zjx0905 0dc58a4b0c feat: 提供更多可使用的类型 2023-04-18 11:14:57 +08:00
zjx0905 fd07afa0a0 build: 修改 rollup 配置 2023-04-18 10:16:35 +08:00
zjx0905 fb4762d01a fix: 错误处理不是每次出错都执行 2023-04-18 10:11:29 +08:00
zjx0905 78eaec150d ci: 添加文档部署脚本 2023-04-17 22:07:38 +08:00
zjx0905 b0eaa04c66 feat: 从参数中删除动态地址属性 2023-04-17 21:31:03 +08:00
zjx0905 b5730304ba chore: 移除 postinstall 2023-04-17 19:51:59 +08:00
zjx0905 cbcc43ad77 feat: 支持清空拦截器 2023-04-17 19:28:45 +08:00
zjx0905 09ac2a94e2 ci: 更改发版和文档部署流程 2023-04-17 14:12:52 +08:00
zjx0905 d065103c70 chore: 移除 js 文件 2023-04-17 00:00:45 +08:00
zjx0905 f2d855d25a docs: 新增菜单 2023-04-16 21:18:04 +08:00
zjx0905 bb7d822643 docs: 补充介绍适配器 2023-04-16 20:47:04 +08:00
zjx0905 6fd68c7be0 docs: 介绍适配器 2023-04-16 20:26:23 +08:00
zjx0905 61263966ad docs: 介绍创建实例和派生领域 2023-04-16 17:52:57 +08:00
zjx0905 47b5fd2716 docs: 介绍拦截器 2023-04-16 16:02:18 +08:00
zjx0905 a3a55021f5 chore: release v2.2.0 2023-04-16 13:47:01 +08:00
zjx0905 021e05233a fix: 修复 Proxy uni 错误 2023-04-16 13:43:28 +08:00
zjx0905 2c3ff567c1 feat: 仅 post/put/patch 方法允许设置请求数据 2023-04-16 13:39:10 +08:00
zjx0905 ab6fd668c0 docs: 新建大纲 2023-04-16 00:01:40 +08:00
zjx0905 b1ce4a37fe docs: 移除旧版本 2023-04-15 16:21:54 +08:00
zjx0905 afc02415ee docs: 介绍 response 2023-04-15 12:20:09 +08:00
zjx0905 d93d949a3b docs: 添加 algolia 2023-04-15 10:29:56 +08:00
zjx0905 9e28effdf5 docs: 新增编辑和更新时间 2023-04-14 23:15:49 +08:00
zjx0905 22bcefcb97 feat: 支持 HTTP PATCH 请求 2023-04-14 18:16:39 +08:00
zjx0905 6550415e29 docs: 基础介绍 2023-04-14 16:38:25 +08:00
zjx0905 a60c649aef ci: 修改测试覆盖率上报参数 2023-04-13 20:11:43 +08:00
zjx0905 220d476c96 docs: 调整颜色 2023-04-13 18:26:35 +08:00
zjx0905 767408c2a3 docs: 自定义主题 2023-04-13 14:16:11 +08:00
zjx0905 376380f7b0 docs: 添加致贡献者 2023-04-12 21:21:03 +08:00
zjx0905 518b98a222 docs: 更新首页 2023-04-12 17:36:05 +08:00
zjx0905 bb18e385bd docs: 支持 PWA 2023-04-11 22:09:29 +08:00
zjx0905 75b8bff470 docs: 介绍 fork 的使用方式 2023-04-11 16:26:13 +08:00
zjx0905 d9fbf121e5 docs: 重构 docs 2023-04-11 16:10:23 +08:00
zjx0905 85f99e3a5e chore: release v2.1.0 2023-04-11 15:56:48 +08:00
zjx0905 8aca3be4fc build: 清理异常 2023-04-11 15:40:46 +08:00
zjx0905 05aa4955f4 chore: 展示 Codecov 徽章 2023-04-11 13:55:19 +08:00
zjx0905 68cbd7a56c ci: 上报测试覆盖率 2023-04-11 13:34:20 +08:00
zjx0905 be17ba7e68 feat: 适配器异常处理成响应异常 2023-04-11 13:13:45 +08:00
zjx0905 adb9dbe88f test: 测试覆盖率 💯 2023-04-10 22:53:15 +08:00
zjx0905 4ba1249146 test: 增加测试覆盖率 2023-04-10 18:53:21 +08:00
zjx0905 d57b82c74e build: 封装 resolve 2023-04-10 15:12:28 +08:00
zjx0905 e180558b25 chore: 添加问题模版 2023-04-10 15:03:59 +08:00
zjx0905 3143ba419e test: 增加测试覆盖率 2023-04-09 22:07:20 +08:00
zjx0905 ee588f6941 test: 测试 dispatchRequest 2023-04-09 21:01:43 +08:00
zjx0905 4c75fa3d32 refactor: 重建响应数据类型 2023-04-09 15:20:10 +08:00
zjx0905 ee6a31b4bb feat: 修改 mergeConfig 中 data 的合并方式 2023-04-08 22:37:50 +08:00
zjx0905 ff3f50a580 docs: 更新 README 2023-04-07 22:07:13 +08:00
zjx0905 a02a4c7e4f refactor: 添加英文的异常信息 2023-04-07 21:24:23 +08:00
zjx0905 21e7058a75 chore: 更新 package.json 2023-04-07 20:38:29 +08:00
zjx0905 2254e73cf7 fix: 修复 axios.fork() 无法访问私有方法 2023-04-07 15:18:05 +08:00
zjx0905 40f1f77d46 refactor: 重构 request 提高可读性 2023-04-07 13:50:08 +08:00
zjx0905 3d137333e0 refactor: 使用 isAxiosError 判断错误类型 2023-04-07 12:51:18 +08:00
zjx0905 22f65cf69c feat: 支持深度合并 params & data 2023-04-07 12:39:23 +08:00
zjx0905 1c09ffdd91 fix: 移除 url 末尾的斜线 2023-04-07 08:47:54 +08:00
zjx0905 222b935f68 feat: 添加新功能 派生领域 axios.fork() 2023-04-06 22:59:49 +08:00
zjx0905 43c18d1723 refactor: 使用新的私有属性语法 2023-04-06 16:00:04 +08:00
zjx0905 69044f3583 feat: fileName 替换为 name 2023-04-06 15:16:12 +08:00
zjx0905 4116df95eb ci: 严格的正则 2023-04-06 13:41:34 +08:00
zjx0905 d4de7df036 chore: release v2.0.0 2023-04-05 17:17:21 +08:00
zjx0905 ce158a2bbb chore: 更新许可证 2023-04-05 17:00:18 +08:00
zjx0905 cf2e46476d refactor: 重写 AxiosError 类型 2023-04-05 16:35:25 +08:00
zjx0905 f1c0f348be docs: 上传和下载使用介绍 2023-04-05 15:24:27 +08:00
zjx0905 61337a9bbe feat: 添加新的 API isAxiosError 2023-04-05 13:31:48 +08:00
zjx0905 7e29e91f0a fix: 修复 dynamicURL 错误匹配端口号 2023-04-05 12:21:26 +08:00
zjx0905 30c3503b22 ci: 优化 pre-commit 2023-04-05 09:29:20 +08:00
zjx0905 2793dd8b5e feat: 优化 defaults
BREAKING CHANGE :
移除了 headers 中 post,put 默认值
2023-04-05 09:15:05 +08:00
zjx0905 897f3bb1f4 chore: release v2.0.0-beta.10 2023-04-05 08:44:29 +08:00
zjx0905 b66176f0ed feat: 支持 es2015 2023-04-05 08:40:00 +08:00
zjx0905 73ac18dee3 ci: 修改 body_path 2023-04-04 10:45:58 +08:00
194 changed files with 26844 additions and 3807 deletions

View File

@ -1,50 +1,52 @@
const { execSync } = require('child_process');
const { execSync } = require('child_process')
const metas = [
{ type: 'feat', section: '✨ Features | 新功能' },
{ type: 'fix', section: '🐛 Bug Fixes | Bug 修复' },
{ type: 'test', section: '✅ Tests | 测试' },
{ type: 'docs', section: '📝 Documentation | 文档' },
{ type: 'build', section: '👷‍ Build System | 构建' },
{ type: 'ci', section: '🔧 Continuous Integration | CI 配置' },
{ type: 'perf', section: '⚡ Performance Improvements | 性能优化' },
{ type: 'revert', section: '⏪ Reverts | 回退' },
{ type: 'chore', section: '📦 Chores | 其他更新' },
{ type: 'style', section: '💄 Styles | 风格', hidden: true },
{ type: 'refactor', section: '♻ Code Refactoring | 代码重构' },
];
{ type: 'feat', section: '✨ Features | 新功能' },
{ type: 'fix', section: '🐛 Bug Fixes | Bug 修复' },
{ type: 'test', section: '✅ Tests | 测试' },
{ type: 'docs', section: '📝 Documentation | 文档' },
{ type: 'build', section: '👷‍ Build System | 构建' },
{ type: 'ci', section: '🔧 Continuous Integration | CI 配置' },
{ type: 'perf', section: '⚡ Performance Improvements | 性能优化' },
{ type: 'revert', section: '⏪ Reverts | 回退' },
{ type: 'chore', section: '📦 Chores | 其他更新' },
{ type: 'style', section: '💄 Styles | 风格', hidden: true },
{ type: 'refactor', section: '♻ Code Refactoring | 代码重构' },
]
/** @type {import('cz-git').UserConfig} */
module.exports = {
rules: {
// @see: https://commitlint.js.org/#/reference-rules
'subject-min-length': [0, 'always', 3],
'subject-max-length': [0, 'always', 80],
'type-enum': [0, 'always', metas.map((meta) => meta.type)],
},
prompt: {
messages: {
type: '请选择提交类型',
subject: '请输入变更描述',
breaking: '列举非兼容性重大的变更,如果有多行,使用 "|" 换行(选填项)\n',
footer: '列举关联的 issue例如#31,#I3244选填项\n',
confirmCommit: '确定提交',
},
types: metas.map((meta) => ({
value: meta.type,
name: `${`${meta.type}:`.padEnd(10, ' ')}${meta.section}`,
})),
allowBreakingChanges: ['feat', 'fix'],
skipQuestions: ['scope', 'body', 'footerPrefix'],
formatMessageCB: (commit) =>
`${commit?.defaultMessage}\n\nCo-authored-by: ${readGitUser(
'name',
)} <${readGitUser('email')}>`,
},
};
rules: {
// @see: https://commitlint.js.org/#/reference-rules
'subject-min-length': [0, 'always', 3],
'subject-max-length': [0, 'always', 80],
'type-enum': [0, 'always', metas.map((meta) => meta.type)],
},
prompt: {
messages: {
type: '请选择提交类型',
subject: '请输入变更描述',
breaking: '列举非兼容性重大的变更,如果有多行,使用 "|" 换行(选填项)\n',
footer: '列举关联的 issue例如#31,#I3244选填项\n',
confirmCommit: '确定提交',
},
types: metas.map((meta) => ({
value: meta.type,
name: `${`${meta.type}:`.padEnd(10, ' ')}${meta.section}`,
})),
allowBreakingChanges: ['feat', 'fix'],
skipQuestions: ['scope', 'body', 'footerPrefix'],
formatMessageCB: (commit) =>
`${commit?.defaultMessage}\n\nCo-authored-by: ${readGitUser(
'name',
)} <${readGitUser('email')}>`,
},
}
function readGitUser(key) {
return execSync(`git config user.${key}`)
.toString()
.replace(/(\r\n\t|\n|\r\t)/g, '');
return execSync(`git config user.${key}`, {
stdio: 'pipe',
})
.toString()
.replace(/(\r\n\t|\n|\r\t)/g, '')
}

View File

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

16
.eslintrc Normal file
View File

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

View File

@ -1,14 +0,0 @@
{
"env": {
"es2022": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"root": true,
"rules": {
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0
}
}

49
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,49 @@
name: 🐞 问题报告
description: 报告 axios-miniprogram 的问题。
labels: [pending triage]
body:
- type: markdown
attributes:
value: |
感谢您花时间填写此错误报告!
- type: textarea
id: bug-description
attributes:
label: 描述错误
description: 对错误是什么的清晰简洁的描述。如果您打算为此问题提交 PR请在描述中告诉我们。谢谢
placeholder: 发表评论
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: 附加上下文
description: 有关问题的任何其他上下文或屏幕截图。
- type: dropdown
id: package-manager
attributes:
label: 使用过的包管理器
description: 选择使用的包管理器
options:
- npm
- yarn
- pnpm
- 源码包(指直接下载 zip 文件的方式)
validations:
required: true
- type: checkboxes
id: checkboxes
attributes:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)以避免创建重复。
required: true
- label: 确保这是 axios-miniprogram 问题而不是特定于框架的问题。
required: true

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1 @@
blank_issues_enabled: false

View File

@ -0,0 +1,44 @@
name: 🚀 新功能提案
description: 提出要添加到 axios-miniprogram 的新功能
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
感谢您对该项目的关注并抽出宝贵时间填写此专题报告!
- type: textarea
id: feature-description
attributes:
label: 清晰简洁的问题描述
description: '作为使用 axios-miniprogram 的开发人员,我想要 [目标/愿望] 以便 [受益]。如果您打算为此问题提交 PR请在描述中告诉我们。谢谢'
validations:
required: true
- type: textarea
id: suggested-solution
attributes:
label: 建议的解决方案
description: '我们可以提供以下实现......'
validations:
required: true
- type: textarea
id: alternative
attributes:
label: 选择
description: 清晰简洁地描述您考虑过的任何替代解决方案或功能。
- type: textarea
id: additional-context
attributes:
label: 附加上下文
description: 有关功能请求的任何其他上下文或屏幕截图。
- type: checkboxes
id: checkboxes
attributes:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true

View File

@ -24,7 +24,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -33,16 +33,27 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Lint
run: pnpm lint
- name: Build
- name: Build all
run: pnpm build -a
- name: Build asset
run: pnpm build:asset
- name: Build assets
run: pnpm build:assets
- name: Typecheck
run: pnpm typecheck
- name: Test
run: pnpm test
run: pnpm test:cov
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./test/.coverage/clover.xml
flags: unittests
verbose: true

View File

@ -2,17 +2,10 @@ name: Deploy Docs
on:
push:
tags:
- v*
branches:
- main
paths:
- 'docs/**'
- '**.md'
pull_request:
branches:
- main
paths:
- 'docs/**'
- '**.md'
- docs
workflow_dispatch:
jobs:
@ -25,7 +18,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -34,7 +27,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Build
run: pnpm docs:build

View File

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

View File

@ -15,7 +15,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Set node
uses: actions/setup-node@v3
@ -24,7 +24,13 @@ jobs:
cache: pnpm
- name: Install
run: pnpm i
run: pnpm install --no-frozen-lockfile
- name: Build Release Assets
run: pnpm build:assets
- name: Create releaselog
run: pnpm releaselog
- name: Check prerelease
id: prerelease
@ -33,22 +39,12 @@ jobs:
script: return /-/.test("${{ github.ref }}")
- name: Create Release
id: create_release
uses: actions/create-release@v1
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
body: 'CHANGELOG.md'
name: Release ${{ github.ref_name }}
prerelease: ${{ steps.prerelease.outputs.result }}
- name: Build Release Asset
run: pnpm build:asset
- name: Upload Release Asset
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_ID: ${{ steps.create_release.outputs.id }}
UPLOAD_URL: ${{ steps.create_release.outputs.upload_url }}
run: pnpm upload:asset
body_path: 'RELEASELOG.md'
files: 'dist/**.zip'

10
.gitignore vendored
View File

@ -3,14 +3,15 @@ node_modules
*.log
# Docs
dist
docs/.vitepress/cache
docs/pages/guide/intro.md
# Mac OS
.DS_Store
# Bundle
lib/
dist/
.swc
# Typescript build file
*.tsbuildinfo
@ -19,7 +20,10 @@ lib/
*.test.js
*.test.d.ts
*.test.js.map
coverage
.coverage
# eslint
.eslintcache
# release
RELEASELOG.md

5
.prettierignore Normal file
View File

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

View File

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

45
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,45 @@
# 贡献者契约行为准则
## 我们的承诺
为了营造一个开放和热情的环境,我们作为贡献者和维护者承诺,无论年龄、体型、残疾、种族、性别特征、性别认同如何,参与我们的项目和我们的社区对每个人来说都是一种无骚扰的体验和表达、经验水平、教育、社会经济地位、国籍、个人外表、种族、宗教或性认同和取向。
## 我们的标准
有助于创造积极环境的行为示例包括:
- 使用欢迎和包容的语言
- 尊重不同的观点和经验
- 优雅地接受建设性的批评
- 专注于对社区最有利的事情
- 对其他社区成员表示同情
参与者不可接受的行为示例包括:
- 使用色情语言或图像以及不受欢迎的性关注或挑逗
- 拖钓、侮辱/贬损评论以及人身或政治攻击
- 公开或私下骚扰
- 未经明确许可发布他人的私人信息,例如物理地址或电子地址
- 在专业环境中可以合理地认为不适当的其他行为
## 我们的责任
项目维护者负责阐明可接受行为的标准,并期望采取适当和公平的纠正措施来响应任何不可接受的行为实例。
项目维护者有权利和责任删除、编辑或拒绝不符合本行为准则的评论、提交、代码、维基编辑、问题和其他贡献,或暂时或永久禁止任何贡献者的其他行为他们认为不合适的、威胁性的、冒犯性的或有害的。
## 范围
当个人代表项目或其社区时,本行为准则适用于项目空间和公共空间。代表项目或社区的示例包括使用官方项目电子邮件地址、通过官方社交媒体帐户发帖,或在在线或离线活动中担任指定代表。项目维护者可以进一步定义和阐明项目的表示。
## 执法
可通过 954270063@qq.com 联系项目团队报告辱骂、骚扰或其他不可接受的行为。所有投诉都将得到审查和调查,并将根据情况做出必要且适当的回应。项目团队有义务为事件的报告者保密。具体执行政策的更多细节可能会单独发布。
不善意遵守或执行行为准则的项目维护者可能会面临由项目领导的其他成员确定的暂时或永久的影响。
## 归因
本行为准则改编自 [Contributor Covenant](https://www.contributor-covenant.org) 1.4 版,可在 https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 获取
有关此行为准则的常见问题的答案,请参阅 https://www.contributor-covenant.org/faq

72
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,72 @@
# 贡献
感谢您有兴趣为这个项目做出贡献!
## 发展
### 设置
将此 repo 克隆到本地计算机并安装依赖项。
```bash
pnpm install
```
我们使用 VitePress 进行快速开发和文档编制。可以通过以下方式在本地启动它。
```bash
pnpm docs:dev
```
我们使用 Vitest 进行单元测试。可以通过以下方式在本地启动它。
```bash
pnpm test:watch
```
我们使用 cz-git 交互式进行 git commit。
```bash
git add .
pnpm cz
```
脚本列表
- `pnpm build` 打包源代码
- `pnpm dev` 监听文件变更并运行 `build`
- `pnpm test` 单元测试
- `pnpm test:watch` 监听文件变更并运行 `test`
- `pnpm test:cov` 运行 `test` 并输出测试覆盖率
- `pnpm docs:dev` 启动开发环境的文档服务器
## 贡献
### 现有功能
随意增强现有功能。请尽量不要引入重大更改。
### 新功能
添加新功能有一些注意事项。
- 在你开始工作之前,最好先开一个 [issue](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 来讨论。
- 应该对新功能进行单元测试。
- 应该在文档中添加相关的使用介绍及方法。
## 项目结构
```
src/ - 源代码
docs/ - 文档
test/ - 单元测试
scripts/ - 脚本及工具函数
```
## 代码风格
不用担心代码风格只要安装好开发依赖即可。Git 钩子将在提交时为您格式化和修复它们。
## 谢谢
再次感谢您对本项目感兴趣!你太棒了!

14
LICENSE
View File

@ -1,21 +1,21 @@
MIT License
The MIT License (MIT)
Copyright (c) 2020 初秋
Copyright (c) 2020-present, zjxxxxxxxxx <https://github.com/zjxxxxxxxxx>
Permission is hereby granted, free of charge, to unknown 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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,33 +1,80 @@
# axios-miniprogram
<h1 align="center">axios-miniprogram</h1>
[![npm version](https://badge.fury.io/js/axios-miniprogram.svg)](https://badge.fury.io/js/axios-miniprogram)
[![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)
<p style="text-align: center;" align="center">
<a style="display: inline-block;margin-left: 5px;" href="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci"/>
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram" >
<img src="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/zjxxxxxxxxx/axios-miniprogram" alt="license"/>
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size"/>
</a>
<a style="display: inline-block;" href="https://www.npmjs.org/package/axios-miniprogram">
<img alt="npm" src="https://img.shields.io/npm/dt/axios-miniprogram"/>
</a>
</p>
[中文文档](https://axios-miniprogram.com)
<p style="text-align: center;" align="center">
<a href='https://axios-miniprogram.com'>中文文档</a>
</p>
## 安装
## axios-miniprogram 是什么?
```bash
$ yarn add axios-miniprogram
```
axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库,支持跨平台使用,同时也支持多种导入方式,可用于原生小程序项目,也可用于第三方框架项目,用法上同 [axios](https://github.com/axios/axios.git) 类似。
或者
## 特性
```bash
$ npm i axios-miniprogram
```
## 简介
为小程序平台量身定制的轻量级请求库,请求配置以微信小程序作为标准,其他平台兼容实现。
- 支持 微信小程序、支付宝小程序、百度小程序、字节跳动小程序、QQ 小程序、uniapp。
- 支持 `Typescript`,健全的类型系统,智能的 `IDE` 提示。
- 支持 `Promise`
- 支持 拦截器。
- 支持 动态地址。
- 支持 校验状态码。
- 支持 参数序列化。
- 支持 上传/下载。
- 支持 错误处理。
- 支持 转换数据。
- 支持 取消请求。
- 支持 自定义合法状态码。
- 支持 自定义参数序列化。
- 支持 自定义转换数据。
- 支持 自定义错误处理。
- 支持 自定义平台适配器
- 支持 扩展实例。
- 支持 中间件。
- 支持 拦截器。
- 支持 平台适配器。
## 目前内部支持的平台
- [微信小程序](https://developers.weixin.qq.com/miniprogram/dev/framework/?from=axios-miniprogram)
- [支付宝小程序](https://opendocs.alipay.com/mini/developer/getting-started?from=axios-miniprogram)
- [百度小程序](https://smartprogram.baidu.com/developer/index.html?from=axios-miniprogram)
- [京东小程序](https://mp.jd.com?from=axios-miniprogram)
- [抖音小程序](https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/overview?from=axios-miniprogram)
- [QQ 小程序](https://q.qq.com/wiki/develop/miniprogram/frame/?from=axios-miniprogram)
- [钉钉小程序](https://open.dingtalk.com/document/org/develop-org-mini-programs?from=axios-miniprogram)
- [飞书小程序](https://open.feishu.cn/document/uYjL24iN/uMjNzUjLzYzM14yM2MTN?from=axios-miniprogram)
- [快手小程序](https://mp.kuaishou.com/docs/introduction/quickStart.html?from=axios-miniprogram)
- [360 小程序](https://mp.360.cn/doc/miniprogram/dev/#/f4b41f0cc5683bce78dfadfa7f3c73e7?from=axios-miniprogram)
- [小红书小程序](https://miniapp.xiaohongshu.com/docs/guide/miniIntroduce?from=axios-miniprogram)
## 关于在跨端框架中使用时的支持度
问:在 uni-app 或者 Taro 等等这类跨端框架中使用时,该请求库支持 h5APPvue3 等等吗?
答:该请求库只是对框架提供的请求 API 进行了封装,并没有使用什么黑魔法。理论上来讲,框架支持的平台,该库也必然支持。
有问题欢迎反馈,请尽量把问题提到 [github issues](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 中,这样更容易被我注意到。
[提问点这里](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)
## 跨端框架示例
### 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

@ -1,58 +1,207 @@
import { defineConfig } from 'vitepress';
import { VitePWA } from 'vite-plugin-pwa';
import { linkIntro } from './utils/link-intro';
linkIntro();
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: 'axios-miniprogram',
titleTemplate: ':title - axios',
description: '基于 Promise 的 HTTP 请求库,适用于各大小程序平台。',
srcDir: 'pages',
lastUpdated: true,
cleanUrls: true,
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: '指南', link: '/guide/introduction' },
{ text: '配置', link: '/config/preview' },
{ text: 'API', link: '/api/interceptors' },
{ text: '指南', link: '/guide/intro', activeMatch: '/guide/' },
{ text: '入门', link: '/basics/request', activeMatch: '/basics/' },
{
text: '进阶',
link: '/advanced/middleware',
activeMatch: '/advanced/',
},
],
sidebar: [
{
text: '指南',
items: [
{ text: '简介', link: '/guide/introduction' },
{ text: '快速上手', link: '/guide/quick-start' },
],
},
{
text: '配置',
items: [
{ text: '默认配置', link: '/config/preview' },
{ text: 'method', link: '/config/method' },
{ text: 'dataType', link: '/config/data-type' },
{ text: 'responseType', link: '/config/response-type' },
{ text: 'validateStatus', link: '/config/validate-status' },
{ text: 'paramsSerializer', link: '/config/params-serializer' },
{ text: 'transformRequest', link: '/config/transform-request' },
{ text: 'transformResponse', link: '/config/transform-response' },
{ text: 'errorHandler', link: '/config/error-handler' },
{ text: 'adapter', link: '/config/adapter' },
],
},
{
text: 'API',
items: [
{ text: 'interceptors', link: '/api/interceptors' },
{ text: 'CancelToken', link: '/api/cancel-token' },
{ text: 'isCancel', link: '/api/is-cancel' },
{ text: 'getUri', link: '/api/get-uri' },
{ text: 'create', link: '/api/create' },
{ text: 'Axios', link: '/api/axios' },
],
},
],
sidebar: sidebar(),
socialLinks: [
{ icon: 'github', link: 'https://github.com/zjx0905/axios-miniprogram' },
{
icon: 'github',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram',
},
],
editLink: {
pattern: ({ relativePath }) => {
if (relativePath.endsWith('/intro.md')) {
return 'https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/README.md';
}
return `https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/docs/pages/${relativePath}`;
},
text: '在 GitHub 上编辑此页面',
},
algolia: algolia(),
returnToTopLabel: '返回顶部',
outlineTitle: '导航栏',
outlineTitle: '导航',
darkModeSwitchLabel: '主题',
sidebarMenuLabel: '菜单',
lastUpdatedText: '最后一次更新',
docFooter: {
prev: '上一页',
next: '下一页',
},
footer: {
message:
'根据 <a href="https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/LICENSE">MIT License</a> 发布',
copyright:
'Copyright © 2020-至今 <a href="https://github.com/zjxxxxxxxxx">zjxxxxxxxxx</a>',
},
},
markdown: {
theme: {
light: 'github-light',
dark: 'github-dark',
},
},
vite: {
plugins: [
VitePWA({
outDir: '.vitepress/dist',
manifest: {
name: 'axios-miniprogram',
short_name: 'axios',
theme_color: '#ffffff',
icons: [],
},
}),
],
},
});
function sidebar() {
return [
{
text: '指南',
items: [
{ text: '简介', link: '/guide/intro' },
{ text: '开始', link: '/guide/quick-start' },
],
},
{
text: '入门',
items: [
{ text: '发送请求', link: '/basics/request' },
{ text: '响应体', link: '/basics/response' },
{ text: '错误处理', link: '/basics/error-handler' },
{ text: '动态地址', link: '/basics/dynamic-url' },
{ text: '请求配置', link: '/basics/config' },
{ text: '默认配置', link: '/basics/defaults' },
{ text: '参数系列化', link: '/basics/params-serializer' },
{ text: '转换数据', link: '/basics/transform-data' },
{ text: '下载文件', link: '/basics/download' },
{ text: '上传文件', link: '/basics/upload' },
],
collapsed: false,
},
{
text: '进阶',
items: [
{ text: '中间件', link: '/advanced/middleware' },
{ text: '请求拦截器', link: '/advanced/request-interceptor' },
{ text: '响应拦截器', link: '/advanced/response-interceptor' },
{ text: '取消请求', link: '/advanced/cancel' },
{ text: '创建实例', link: '/advanced/instance' },
{ text: '扩展实例', link: '/advanced/extend' },
{ text: '平台适配器', link: '/advanced/adapter' },
],
collapsed: false,
},
{
text: '请求方法',
items: [
{ text: 'OPTIONS', link: '/method/OPTIONS' },
{ text: 'GET', link: '/method/GET' },
{ text: 'HEAD', link: '/method/HEAD' },
{ text: 'POST', link: '/method/POST' },
{ text: 'PUT', link: '/method/PUT' },
{ text: 'PATCH', link: '/method/PATCH' },
{ text: 'DELETE', link: '/method/DELETE' },
{ text: 'TRACE', link: '/method/TRACE' },
{ text: 'CONNECT', link: '/method/CONNECT' },
],
collapsed: false,
},
{
text: '致贡献者',
items: [
{
text: '行为准则',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md',
},
{
text: '贡献指南',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md',
},
],
},
];
}
function algolia() {
return {
appId: 'B2V3TSSQ2T',
apiKey: '2eddc4539ada25bf664eddcb91930736',
indexName: 'axios-miniprogram',
placeholder: '搜索文档',
translations: {
button: {
buttonText: '搜索文档',
buttonAriaLabel: '搜索文档',
},
modal: {
searchBox: {
resetButtonTitle: '清除查询条件',
resetButtonAriaLabel: '清除查询条件',
cancelButtonText: '取消',
cancelButtonAriaLabel: '取消',
},
startScreen: {
recentSearchesTitle: '搜索历史',
noRecentSearchesText: '没有搜索历史',
saveRecentSearchButtonTitle: '保存至搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除',
},
errorScreen: {
titleText: '无法获取结果',
helpText: '你可能需要检查你的网络连接',
},
footer: {
selectText: '选择',
navigateText: '切换',
closeText: '关闭',
searchByText: '搜索提供者',
},
noResultsScreen: {
noResultsText: '无法找到相关结果',
suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为该查询应该有结果?',
reportMissingResultsLinkText: '点击反馈',
},
},
},
};
}

View File

@ -0,0 +1,68 @@
<script setup lang="ts">
import { computed } from 'vue';
import { isString } from 'lodash-es';
type Support = boolean | string;
interface VPCompatibilityProps {
wx?: Support;
my?: Support;
swan?: Support;
tt?: Support;
tt2?: Support;
qq?: Support;
ks?: Support;
dd?: Support;
jd?: Support;
qh?: Support;
}
const props = defineProps<VPCompatibilityProps>();
const metas = [
{ name: '微信小程序', id: 'wx' },
{ name: '支付宝小程序', id: 'my' },
{ name: '百度小程序', id: 'swan' },
{ name: '京东小程序', id: 'jd' },
{ name: '抖音小程序', id: 'tt' },
{ name: 'QQ 小程序', id: 'qq' },
{ name: '钉钉小程序', id: 'dd' },
{ name: '飞书小程序', id: 'tt2' },
{ name: '快手小程序', id: 'ks' },
{ name: '360 小程序', id: 'qh' },
];
const platforms = computed(() => {
return metas.map(({ name, id }) => {
const prop = props[id as keyof VPCompatibilityProps];
const support = isString(prop) ? prop : prop ? '✓' : '✗ ';
return {
name,
support,
};
});
});
defineExpose({
platforms,
props,
});
</script>
<template>
<table>
<thead>
<tr>
<th>平台</th>
<th>支持度</th>
</tr>
</thead>
<tbody>
<tr v-for="platform in platforms">
<td style="text-align: left">{{ platform.name }}</td>
<td style="text-align: left">{{ platform.support }}</td>
</tr>
</tbody>
</table>
</template>

View File

@ -0,0 +1,13 @@
import { EnhanceAppContext } from 'vitepress';
import DefaultTheme from 'vitepress/theme';
import VPCompatibility from './components/VPCompatibility.vue';
import './styles/vars.css';
import './styles/cover.css';
export default {
extends: DefaultTheme,
enhanceApp(ctx: EnhanceAppContext) {
ctx.app.component('VPCompatibility', VPCompatibility);
},
};

View File

@ -0,0 +1,218 @@
.VPNavBar.has-sidebar {
background-color: var(--vp-nav-bg-color);
border-bottom-color: var(--vp-c-gutter) !important;
}
.VPNavBar .title {
border-bottom: none;
}
.VPNavBar .content-body {
background-color: transparent !important;
}
.VPNavBar .curtain,
.VPSidebar .curtain {
display: none;
}
.VPSidebar {
margin-top: var(--vp-nav-height);
padding-top: 40px !important;
height: calc(100% - var(--vp-nav-height));
transition: transform 0.3s cubic-bezier(0.19, 1, 0.22, 1) !important;
}
.VPSidebar.open {
margin-top: 0;
height: 100%;
background-color: var(--vp-nav-bg-color);
}
.VPSidebar .group {
width: 100%;
}
.VPSidebarItem.level-0 .text {
font-size: 15px;
font-weight: 500 !important;
}
.VPSidebarItem.level-1 .text {
padding-left: 1em;
font-size: 14px;
color: var(--vp-c-text-1) !important;
font-weight: normal !important;
}
.VPSidebarItem.level-1.is-active .text {
color: var(--vp-c-brand) !important;
font-weight: 500 !important;
}
.VPSidebarItem.level-1.is-active .text::before {
content: '';
display: block;
width: 4px;
height: 4px;
border-radius: 2px;
background-color: var(--vp-c-brand);
position: absolute;
top: 15px;
left: 2px;
}
.VPDocAside .content {
border-left: none;
}
.VPDocAside .outline-title {
font-size: 14px;
font-weight: normal;
}
.VPDocAside .outline-marker {
left: 4px;
width: 4px;
height: 4px;
border-radius: 2px;
transform: translateY(7px);
}
.VPDocAside .outline-link {
position: relative;
font-weight: normal;
font-size: 14px;
}
.VPDocAside .outline-link.active {
color: var(--vp-c-brand);
font-weight: bold;
}
.VPBackdrop {
backdrop-filter: blur(16px);
background-color: transparent !important;
transition: none !important;
}
.VPLocalNavOutlineDropdown .items {
overflow: auto;
}
.VPMenu {
border: 1px solid var(--vp-c-gutter) !important;
border-radius: 6px !important;
box-shadow: none !important;
}
.VPHero .tagline {
font-weight: normal;
}
.VPFeature {
border: none;
border-radius: 8px;
}
.VPFeature .box {
padding: 32px;
}
.VPFeature .icon {
margin-bottom: 24px;
}
.VPFeature .details {
font-weight: normal;
}
.VPFeature .box {
padding: 32px;
}
.VPFooter .message,
.VPFooter .copyright {
color: var(--vp-c-text-3);
font-weight: normal;
}
.VPContent a {
color: var(--vp-c-link);
}
.language-bash,
.language-ts {
border-radius: none;
border: none;
}
.vp-code-group .tabs {
border-color: var(--vp-c-gutter);
}
.vp-code-group .tabs label::after {
z-index: 1;
}
.DocSearch-Container {
backdrop-filter: blur(16px);
}
.DocSearch-Modal {
--docsearch-modal-background: var(--vp-code-copy-code-bg);
box-shadow: none;
}
.DocSearch-Logo svg > * {
fill: currentColor;
}
.custom-block {
border-radius: 6px;
background-color: var(--vp-custom-block-tip-bg) !important;
}
.dark .DocSearch-Modal {
--docsearch-modal-background: var(--vp-c-bg-soft);
}
.dark .DocSearch-Form {
background-color: var(--vp-code-block-bg);
}
.dark .DocSearch-Logo svg > * {
fill: currentColor;
}
@media (min-width: 960px) {
.VPFeatures .item {
width: calc(100% / 2) !important;
}
}
@media (min-width: 768px) {
.DocSearch-Button {
border: 1px solid var(--vp-c-gutter);
}
}
@media (min-width: 640px) {
.VPFeatures .item {
width: 100%;
}
.language-bash,
.language-ts {
border-radius: 6px;
}
.prev-next {
justify-content: space-between;
}
.pager {
width: auto !important;
min-width: 180px;
}
}

View File

@ -0,0 +1,76 @@
:root {
--vp-c-brand: #07c160;
--vp-c-brand-light: rgb(7, 193, 96, 0.8);
--vp-c-brand-lighter: rgb(7, 193, 96, 0.6);
--vp-c-brand-dark: #07c160;
--vp-c-brand-darker: #07c160;
--vp-c-text-light-1: #000;
--vp-c-text-light-2: #888;
--vp-c-text-light-3: #b2b2b2;
--vp-c-text-code: #000000;
--vp-c-text-dark-3: #888;
--vp-code-tab-text-color: var(--vp-c-text-light-2);
--vp-code-tab-active-text-color: var(--vp-c-text-light-1);
--vp-code-tab-hover-text-color: var(--vp-c-text-light-1);
--vp-code-tab-divider: var(--vp-c-gutter);
--vp-code-block-bg-light: #ffffff;
--vp-code-block-bg: #f9f9fa;
--vp-code-copy-code-active-text: #808080;
--vp-code-copy-code-bg: #ffffff;
--vp-code-copy-code-hover-bg: #f3f4f6;
--vp-code-copy-code-border-color: rgba(31, 35, 40, 0.15);
--vp-code-copy-code-hover-border-color: rgba(31, 35, 40, 0.15);
--vp-c-mute: #f9f9fa;
--vp-c-gutter: rgba(0, 0, 0, 0.06);
--vp-c-link: #576b95;
--vp-c-bg: #ffffff;
--vp-c-bg-alt: #00000003;
--vp-c-bg-soft: var(--vp-c-bg-alt);
--vp-button-alt-bg: #ffffff;
--vp-button-alt-hover-bg: var(--vp-c-bg-alt);
--vp-nav-bg-color: #f7f7f7;
--vp-custom-block-tip-border: var(--vp-c-brand);
--vp-custom-block-tip-text: var(--vp-c-brand);
--vp-custom-block-tip-bg: var(--vp-c-bg);
--docsearch-container-background: rgba(0, 0, 0, 0.02);
--docsearch-logo-color: var(--vp-c-brand);
--vp-sidebar-width: 340px;
}
.dark {
--vp-c-text-dark-1: #ffffff;
--vp-c-text-code: #ffffff;
--vp-code-tab-active-text-color: var(--vp-c-text-dark-1);
--vp-code-tab-hover-text-color: var(--vp-c-text-dark-1);
--vp-code-block-bg: #0d1117;
--vp-c-bg: #020409;
--vp-c-bg-alt: #0d1117;
--vp-nav-bg-color: #161b22;
--vp-c-mute: #313136;
--vp-c-gutter: #30363d;
--vp-c-link: #2f81f7;
--vp-button-alt-bg: #21262d;
--vp-c-bg-elv: #0d1117;
--vp-code-copy-code-bg: #21262d;
--vp-code-copy-code-hover-bg: #21262d;
--vp-code-copy-code-border-color: rgba(240, 246, 252, 0.1);
--vp-code-copy-code-hover-border-color: #8b949e;
--docsearch-container-background: rgba(255, 255, 255, 0.08);
}
.dark .DocSearch {
--docsearch-logo-color: var(--vp-c-brand);
}

View File

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

View File

@ -1,19 +0,0 @@
# Axios
## `axios.Axios`
`axios.Axios`是一个类,其实`axios`就是`axios.Axios`类的实例改造而来的,`axios.create(defaults)`创建的也是`axios.Axios`的实例。
直接实例化`axios.Axios`可以得到一个`原始实例`,不能当函数调用,传入的自定义配置就是`原始实例`的默认配置,而不会像`axios.create(defaults)`一样去合并`axios`中的默认配置。
```typescript
const instance = new axios.Axios({
beseURL: 'https://www.api.com',
params: {
id: 1,
},
});
instance.get('/user');
// 'https://www.api.com/user?id=1'
```

View File

@ -1,29 +0,0 @@
# CancelToken
## `axios.CancelToken`取消令牌
可以使用`CancelToken`取消已经发出的请求。
```typescript
let cancel;
axios('/api', {
cancelToken: new axios.CancelToken(function (c) {
cancel = c;
}),
});
cancel('取消请求');
```
还可以使用`CancelToken.source`工厂方法创建`CancelToken`。
```typescript
const source = axios.CancelToken.source();
axios('/api', {
cancelToken: source.token,
});
source.cancel('取消请求');
```

View File

@ -1,20 +0,0 @@
# create
## `axios.create(defaults)`
创建一个`自定义实例`,传入的自定义默认配置`defaults`会和`axios`的默认配置`axios.defaults`合并成`自定义实例`的默认配置。
`自定义实例`拥有和`axios`相同的调用方式和请求方法的别名。
```typescript
axios.defaults.baseURL = 'https://www.api.com';
const instance = axios.create({
params: {
id: 1,
},
});
instance('/user');
// 'https://www.api.com/user?id=1'
```

View File

@ -1,15 +0,0 @@
# getUri
## `axios.getUri(config)`
根据配置中的`url`和`params`生成一个`URI`。
```typescript
const uri = axios.getUri({
url: '/user',
params: {
id: 1,
},
});
// '/user?id=1'
```

View File

@ -1,49 +0,0 @@
# interceptors
## `axios.interceptors`拦截器
可以先拦截请求或响应,然后再由 then 或 catch 处理。
```typescript
// 添加请求拦截器
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
//处理请求错误
return Promise.reject(error);
},
);
// 添加响应拦截器
axios.interceptors.response.use(
function (response) {
// 请求成功后做些什么
return response;
},
function (error) {
// 处理响应错误
return Promise.reject(error);
},
);
```
如果以后需要删除拦截器,则可以。
```typescript
const myInterceptor = axios.interceptors.request.use(function () {
// 在发送请求之前做些什么
});
axios.interceptors.request.eject(myInterceptor);
```
还可以将拦截器添加到`axios`的`自定义实例`中。
```typescript
const myInterceptor = instance.interceptors.request.use(function () {
// 在发送请求之前做些什么
});
instance.interceptors.request.eject(myInterceptor);
```

View File

@ -1,13 +0,0 @@
# isCancel
## `axios.isCancel`是否取消
可以判断当前错误是否来自取消请求
```typescript
axios('/user').catch((error) => {
if (axios.isCancel(error)) {
// 请求被取消了
}
});
```

View File

@ -1,65 +0,0 @@
# adapter
## 自定义平台适配器`config.adapter`
您可以手动适配当前所处的平台。
```typescript
axios.defaults.adapter = function adapter(adapterConfig) {
const {
// 请求类型
type,
// 请求地址
url,
// 请求方法
method,
// 请求参数
params,
// 请求数据
data,
// 请求头 同 headers
headers,
// 响应数据格式
dataType,
// 响应数据类型
responseType,
// 超时时间
timeout,
// 成功的回调函数
success,
// 失败的回调函数
fail,
} = adapterConfig;
// 在 adapterConfig 中选择您需要的参数发送请求
switch (type) {
case 'request': // 数据请求
return wx.request({
url,
method,
data,
header: headers,
success,
fail,
});
case 'upload': // 上传
return wx.uploadFile({
url,
method,
formData: data,
header: headers,
success,
fail,
});
case 'download': // 下载
return wx.downloadFile({
url,
method,
filePath: params.filePath,
header: headers,
success,
fail,
});
}
};
```

View File

@ -1,8 +0,0 @@
# dataType
## `config.dataType`的合法值
| 值 | 说明 | 全平台兼容 |
| :--- | :--------------------------------------------------------- | :--------- |
| json | 返回的数据为 JSON返回后会对返回的数据进行一次 JSON.parse | 是 |
| 其他 | 不对返回的内容进行 JSON.parse | 是 |

View File

@ -1,30 +0,0 @@
# errorHandler
## 自定义错误处理`config.errorHandler`
可以添加到默认配置中,统一处理错误。
```typescript
axios.defaults.errorHandler = function errorHandler(error) {
// 做一些想做的事情
return Promise.reject(error);
};
const instance = axios.create({
errorHandler: function errorHandler(error) {
// 做一些想做的事情
return Promise.reject(error);
},
});
```
也可以发送请求时通过自定义配置传入。
```typescript
axios('/user', {
errorHandler: function errorHandler(error) {
// 做一些想做的事情
return Promise.reject(error);
},
});
```

View File

@ -1,16 +0,0 @@
# method
## `config.method`的合法值
可以使用大写,也可以使用小写。
| 值 | 说明 | 全平台兼容 |
| :------ | :--- | :--------- |
| OPTIONS | | |
| GET | | 是 |
| HEAD | | |
| POST | | 是 |
| PUT | | 是 |
| DELETE | | 是 |
| TRACE | | |
| CONNECT | | |

View File

@ -1,15 +0,0 @@
# paramsSerializer
## 自定义参数序列化`config.paramsSerializer`
可以使用自己的规则去序列化参数。
```typescript
axios('/user', {
paramsSerializer: function paramsSerializer(params) {
return qs.stringify(params, {
arrayFormat: 'brackets',
});
},
});
```

View File

@ -1,69 +0,0 @@
# 默认配置
## 全局默认配置`axios.defaults`
```typescript
axios.defaults.baseURL = 'https://www.api.com';
axios.defaults.headers.common['Accept'] = 'application/json, test/plain, */*';
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
```
## 自定义实例默认配置
可以创建时传入。
```typescript
const instance = axios.create({
baseURL: 'https://www.api.com',
headers: {
common: {
Accept: 'application/json, test/plain, */*',
},
post: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
},
},
});
```
也可以创建后修改。
```typescript
instance.defaults.baseURL = 'https://www.api.com';
instance.defaults.headers.common['Accept'] =
'application/json, test/plain, */*';
instance.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
```
## 配置优先顺序
发送请求时,会使用默认配置`defaults`和自定义配置`config`合并出请求配置`requestConfig`,然后用合并出的请求配置`requestConfig`去发送请求,多数情况下,后者优先级要高于前者,具体合并策略可以参考 [mergeConfig.ts](https://github.com/early-autumn/axios-miniprogram/blob/master/src/core/mergeConfig.ts) 的实现。
## 配置表
非全平台兼容的属性只会在平台支持的情况下生效。
| 参数 | 类型 | 默认值 | 说明 | 全平台兼容 |
| :---------------- | :-----------------------: | :------------------------------------------------------------------------------------ | :----------------- | :--------- |
| adapter | Function | [查看](https://github.com/early-autumn/axios-miniprogram/blob/master/src/defaults.ts) | 自定义适配器 | 是 |
| baseURL | String | | 基础地址 | 是 |
| url | String | | 请求地址 | 是 |
| method | String | get | 请求方法 | |
| params | Object | | 请求参数 | 是 |
| data | String/Object/ArrayBuffer | | 请求数据 | 是 |
| headers | Object | [查看](https://github.com/early-autumn/axios-miniprogram/blob/master/src/defaults.ts) | 请求头 | 是 |
| validateStatus | Function | [查看](https://github.com/early-autumn/axios-miniprogram/blob/master/src/defaults.ts) | 自定义合法状态码 | 是 |
| paramsSerializer | Function | | 自定义参数序列化 | 是 |
| transformRequest | Function/Array\<Function> | | 自定义转换请求数据 | 是 |
| transformResponse | Function/Array\<Function> | | 自定义转换响应数据 | 是 |
| errorHandler | Function | | 自定义错误处理 | 是 |
| cancelToken | Object | | 取消令牌 | 是 |
| timeout | Number | 10000 | 超时时间 | |
| dataType | String | json | 响应数据格式 | 是 |
| responseType | String | text | 响应数据类型 | 是 |
| enableHttp2 | Boolean | false | 开启 http2 | |
| enableQuic | Boolean | false | 开启 quic | |
| enableCache | Boolean | false | 开启 cache | |
| sslVerify | Boolean | true | 验证 ssl 证书 | |

View File

@ -1,8 +0,0 @@
# responseType
## `config.responseType`的合法值
| 值 | 说明 | 全平台兼容 |
| :---------- | :----------------------- | :--------- |
| text | 响应的数据为文本 | 是 |
| arraybuffer | 响应的数据为 ArrayBuffer | 是 |

View File

@ -1,16 +0,0 @@
# transformRequest
## `config.transformRequest`自定义转换请求数据
可以在请求发出之前转换请求数据。
```typescript
axios('/user', {
transformRequest: [
function transformRequest(data, headers) {
// 转换请求数据
return data;
},
],
});
```

View File

@ -1,16 +0,0 @@
# transformResponse
## `config.transformResponse`自定义转换响应数据
可以在请求发出之前转换请求数据。
```typescript
axios('/user', {
transformResponse: [
function transformResponse(data, headers) {
// 转换请求数据
return data;
},
],
});
```

View File

@ -1,14 +0,0 @@
# validateStatus
## 自定义合法状态码`config.validateStatus`
可以让请求按照您的要求成功或者失败。
```typescript
axios('/user', {
validateStatus: function validateStatus(status) {
// 这样,状态码在 200 到 400 之间都是请求成功
return status >= 200 && status < 400;
},
});
```

5
docs/global.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent;
export default component;
}

View File

@ -1,26 +0,0 @@
---
title: 简介
sidebarDepth: 1
lastUpdated: true
sitemap:
priority: 0.8
---
# 简介
## 什么是 axios-miniprogram
axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库,支持跨平台使用,同时也支持多种导入方式,可用于原生小程序项目,也可用于第三方框架项目,用法上同 [axios](git@github.com:axios/axios.git) 类似。
## 特性
- 支持 微信小程序、支付宝小程序、百度小程序、字节跳动小程序、QQ 小程序、uniapp。
- 支持 `Typescript`,健全的类型系统,智能的 `IDE` 提示。
- 支持 `Promise`
- 支持 拦截器。
- 支持 取消请求。
- 支持 自定义合法状态码。
- 支持 自定义参数序列化。
- 支持 自定义转换数据。
- 支持 自定义错误处理。
- 支持 自定义平台适配器

View File

@ -1,184 +0,0 @@
---
title: 快速上手
sidebarDepth: 1
lastUpdated: true
sitemap:
priority: 0.8
---
# 快速上手
## 安装
:::: code-group
```sh [NPM]
npm install -D axios-miniprogram
```
```sh [YARN]
yarn add -D axios-miniprogram
```
```sh [PNPM]
pnpm install -D axios-miniprogram
```
::::
## 使用
### 如何引入
```typescript
// esm
import axios from 'axios-miniprogram';
// cjs
const axios = require('axios-miniprogram');
// 使用
axios('/user');
```
### `axios(config)`
可以通过将相关配置传递给`axios`来发送请求。
```typescript
// 发送 GET 请求
axios({
url: '/user',
method: 'get',
params: {
id: 1,
},
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
// 发送 POST 请求
axios({
url: '/user',
method: 'post',
data: {
id: 1,
},
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
### `axios(url, config?)`
也可以通过直接把`url`传给`axios`来发送请求。
```typescript
// 默认发送 GET 请求
axios('/user')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
// 发送 POST 请求
axios('/user', {
method: 'post',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
还可以使用请求方法的别名来简化请求。
- ##### axios.request(config)
- ##### axios.options(url, config?)
- ##### axios.get(url, params?, config?)
- ##### axios.head(url, params?, config?)
- ##### axios.post(url, data?, config?)
- ##### axios.put(url, data?, config?)
- ##### axios.delete(url, params?, config?)
- ##### axios.trace(url, config?)
- ##### axios.connect(url, config?)
常用例子,其他同理:
```typescript
// 发送 GET 请求
axios.get('/user');
// 携带参数
axios.get('/user', {
test: 1,
});
// 携带额外配置
axios.get(
'/user',
{
id: 1,
},
{
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
},
);
// 发送 POST 请求
axios.post('/user');
// 携带数据
axios.post('/user', {
id: 1,
});
// 携带额外配置
axios.post(
'/user',
{
id: 1,
},
{
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
},
);
```
## 动态 URL
您可以使用动态 URL 提高 RESTful API 的书写体验。
```typescript
axios.get('/user/:id', {
id: 1,
});
```
## 响应体`response`
非全平台兼容的属性只会在平台支持的情况下生效。
| 属性 | 类型 | 说明 | 全平台兼容 |
| :--------- | :------------------------ | :------------------------------------------- | :--------- |
| status | Number | 状态码 | 是 |
| statusText | String | 状态文本 | 是 |
| data | String/Object/ArrayBuffer | 开发者服务器返回的数据 | 是 |
| headers | Object | 响应头 | 是 |
| config | Object | Axios 请求配置 | 是 |
| cookies | Array<.String> | 开发者服务器返回的 cookies格式为字符串数组 | |
| profile | Object | 网络请求过程中一些关键时间点的耗时信息 | |

View File

@ -1,24 +0,0 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: 'axios-miniprogram'
text: '基于 Promise 的 HTTP 请求库,适用于各大小程序平台。'
tagline: My great project tagline
actions:
- theme: brand
text: 介绍
link: /guide/introduction
- theme: alt
text: 安装
link: /guide/quick-start
features:
- title: 轻量
details: 不足 10kb
- title: 跨平台
details: 兼容各个小程序
- title: 方便
details: 任何形式的项目都可使用
---

View File

@ -7,6 +7,12 @@
"preview": "vitepress preview"
},
"devDependencies": {
"@types/lodash-es": "^4.17.7",
"vite-plugin-pwa": "^0.14.7",
"vitepress": "1.0.0-alpha.61"
},
"dependencies": {
"lodash-es": "^4.17.21",
"vue": "^3.2.47"
}
}
}

View File

@ -0,0 +1,289 @@
---
title: 平台适配器
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于支持更多小程序平台或小程序框架。
适配器是一个函数,它可以接收 `config` 参数。
:::
## 基本配置
可以接收基本配置。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = (config) => {
// 配置项
const {
// 请求类型
// 'request' | 'upload' | 'download'
type,
// 开发者服务器接口地址
url,
// HTTP 请求方法
method,
// 请求参数
params,
// 请求数据
data,
// 请求头
headers,
// 返回的数据格式
dataType,
// 响应的数据类型
responseType,
// 超时时间
timeout,
// 成功的回调
success,
// 失败的回调
fail,
} = config;
};
```
## 其他配置
可以接收任意多个其他配置。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = (config) => {
const {
// 其他配置
other1,
// 其他配置
other2,
} = config;
};
axios('https://api.com', {
other1: true,
other2: true,
});
```
## 实现一个适配器
适配的本质是对配置项进行转换,甚至可以零逻辑完成适配。
这里用适配 uni-app 举例,适配其他平台其实大同小异。
```ts
import axios from 'axios-miniprogram';
// 适配器
axios.defaults.adapter = (config) => {
// 可以先看看 config 上都有哪些属性
console.log(config);
// 开始适配不同类型的请求
switch (config.type) {
case 'request':
// 适配数据请求
return uni.request({
url: config.url,
data: config.data,
header: config.headers,
method: config.method,
timeout: config.timeout,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
withCredentials: config.withCredentials,
firstIpv4: config.firstIpv4,
enableHttp2: config.enableHttp2,
enableQuic: config.enableQuic,
enableCache: config.enableCache,
enableHttpDNS: config.enableHttpDNS,
httpDNSServiceId: config.httpDNSServiceId,
enableChunked: config.enableChunked,
forceCellularNetwork: config.forceCellularNetwork,
enableCookie: config.enableCookie,
cloudCache: config.cloudCache,
defer: config.defer,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: response.data,
// cookie 列表
cookies: response.cookies,
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
case 'upload':
// 适配上传文件
const { files, fileType, file, filePath, name, ...formData } =
config.data;
return uni.uploadFile({
url: config.url,
files,
fileType,
file,
filePath,
name,
formData,
header: config.headers,
timeout: config.timeout,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: response.data,
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
case 'download':
// 适配下载文件
return uni.downloadFile({
url: config.url,
filePath: config.params?.filePath,
header: config.headers,
timeout: config.timeout,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: {
filePath: response.filePath,
tempFilePath: response.tempFilePath,
},
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
}
};
```
## 使用 `createAdapter` 创建适配器
可以使用 `createAdapter` 简化适配流程。
直接使用可以完美适配小程序平台,但不能保证完美适配小程序以外的其他平台,如 App、H5。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = axios.createAdapter({
request: uni.request,
upload: uni.uploadFile,
download: uni.downloadFile,
});
```
也可以进一步抹平存在差异的部分,实现完美适配全平台。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = axios.createAdapter({
request: uni.request,
upload: (config) => {
// 其实差异只有一点点,抹平可以很轻易~
const {
// 需要上传的文件列表
// App、H5 2.6.15+
files,
// 要上传的文件对象
// 仅 H52.6.15+)支持
file,
...formData
} = config.formData;
return uni.uploadFile({
...config,
files,
file,
formData,
});
},
download: uni.downloadFile,
});
```

View File

@ -0,0 +1,81 @@
---
title: 取消请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于取消不再需要响应的请求。
:::
## 取消请求
可以创建一个 `CancelToken` 实例用来取消请求。
```ts
import axios from 'axios-miniprogram';
let cancel;
axios('https://api.com/test', {
cancelToken: new axios.CancelToken((c) => {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
}),
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 取消请求
cancel('request canceled');
```
## 工厂方法
可以用 `CancelToken.source` 工厂方法创建 `CancelToken` 实例用来取消请求。
```ts
import axios from 'axios-miniprogram';
const { cancel, token } = axios.CancelToken.source();
axios('https://api.com/test', {
cancelToken: token,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 取消请求
cancel('request canceled');
```
## 判断取消请求
可以判断请求错误是否来自取消请求,从而做出相应的处理。
```ts
import axios from 'axios-miniprogram';
const { cancel, token } = axios.CancelToken.source();
axios('https://api.com/test', {
cancelToken: token,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 判断取消请求
if (axios.isCancel(error)) {
console.log(error, '请求已被取消');
}
});
// 取消请求
cancel('request canceled');
```

View File

@ -0,0 +1,255 @@
---
title: 扩展实例
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
扩展新的实例,复用拦截器、中间件。
:::
## 扩展实例
可以基于 `axios` 扩展实例,配置项 `baseURL` 传相对地址时会和 `axios.defaults.baseURL` 一起组合成完整的服务端地址。
全局默认配置 `axios.defaults` 和扩展实例时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成实例默认配置 `instance.defaults`
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
// 相对地址会进行组合
// baseURL 最终结果为 https://api.com/user
const instance = axios.extend({
baseURL: 'user',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
// 绝对地址会直接使用
// baseURL 最终结果为 https://api2.com/user
const instance = axios.extend({
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 instance = axios.extend({
baseURL: 'user',
});
instance.defaults.headers.common['Content-Type'] = 'application/json';
instance.defaults.timeout = 1000;
```
## 添加拦截器
可以添加实例的[请求拦截器](/advanced/request-interceptor)和[响应拦截器](/advanced/response-interceptor)。
```ts
import axios from 'axios-miniprogram';
const instance = axios.extend({
baseURL: 'test',
});
// 请求拦截器
instance.interceptors.request.use(
function (config) {
console.log('instance request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
instance.interceptors.response.use(
function (response) {
console.log('instance response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// instance request -> instance response
instance('/');
```
也可以复用拦截器。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
const parent = axios.extend({
baseURL: '/parent',
});
const child = parent.extend({
baseURL: '/child',
});
// 请求拦截器
axios.interceptors.request.use(
function (config) {
console.log('axios request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
axios.interceptors.response.use(
function (response) {
console.log('axios response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> https://api.com/parent/child/ -> axios response
child('/');
// 请求拦截器
parent.interceptors.request.use(
function (config) {
console.log('parent request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
parent.interceptors.response.use(
function (response) {
console.log('parent response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> parent request -> https://api.com/parent/child/ -> parent response -> axios response
child('/');
// 请求拦截器
child.interceptors.request.use(
function (config) {
console.log('child request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
child.interceptors.response.use(
function (response) {
console.log('child response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> parent request -> child request -> https://api.com/parent/child/ -> child response -> parent response -> axios response
child('/');
```
## 使用
使用方式和 `axios` 完全一致。
```ts
const instance = axios.extend({
baseURL: 'https://api.com',
});
instance('test')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance('test', {
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance({
url: 'test',
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
也可以使用请求方法简化请求。
- [instance.request(url, config?) | instance.request(config)](/basics/request)
- [instance.options(url, config?)](/method/OPTIONS)
- [instance.get(url, params?, config?)](/method/GET)
- [instance.head(url, params?, config?)](/method/HEAD)
- [instance.post(url, data?, config?)](/method/POST)
- [instance.put(url, data?, config?)](/method/PUT)
- [instance.patch(url, data?, config?)](/method/PATCH)
- [instance.delete(url, params?, config?)](/method/DELETE)
- [instance.trace(url, config?)](/method/TRACE)
- [instance.connect(url, config?)](/method/CONNECT)

View File

@ -0,0 +1,158 @@
---
title: 创建实例
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
创建新的实例。
:::
## 创建实例
可以使用 `axios.create(config)` 创建新的实例。
全局默认配置 `axios.defaults` 和创建实例时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成实例默认配置 `instance.defaults`
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.com',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
```
## 默认配置
可以设置配置项默认值。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.com',
});
instance.defaults.headers.common['Content-Type'] = 'application/json';
instance.defaults.timeout = 1000;
```
## 添加拦截器
可以添加实例的[请求拦截器](/advanced/request-interceptor)和[响应拦截器](/advanced/response-interceptor)。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.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);
},
);
```
## 扩展实例
可以基于实例[扩展实例](/advanced/extend)。
实例默认配置 `parent.defaults` 和派生领域时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成新实例默认配置 `child.defaults`
```ts
import axios from 'axios-miniprogram';
const parent = axios.create({
baseURL: 'https://api2.com',
});
const child = instance.extend({
baseURL: 'user',
});
// 请求的服务端地址 https://api2.com/user
child('/');
```
## 使用
使用方式和 `axios` 完全一致。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api.com',
});
instance('test')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance('test', {
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance({
url: 'test',
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
也可以使用请求方法简化请求。
- [instance.request(url, config?) | instance.request(config)](/basics/request)
- [instance.options(url, config?)](/method/OPTIONS)
- [instance.get(url, params?, config?)](/method/GET)
- [instance.head(url, params?, config?)](/method/HEAD)
- [instance.post(url, data?, config?)](/method/POST)
- [instance.put(url, data?, config?)](/method/PUT)
- [instance.patch(url, data?, config?)](/method/PATCH)
- [instance.delete(url, params?, config?)](/method/DELETE)
- [instance.trace(url, config?)](/method/TRACE)
- [instance.connect(url, config?)](/method/CONNECT)

View File

@ -0,0 +1,123 @@
---
title: 中间件
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
基于洋葱模型的中间件。
:::
## 前言
如果您了解或者使用过[koa](https://github.com/koajs/koa),相信您一定十分了解什么是洋葱模型,中间件该怎么写。
中间件是一个异步函数,接收 `context``next` 两个参数。
`context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其组成部分。
- `context.req`:请求配置。
- `context.res`:请求完成后服务端返回的响应体,它的初始值是 `null`,请求完成之后才能对其进行操作。
`next` 是一个异步函数,如果希望程序继续执行后续逻辑,请手动调用它。
```ts
async (ctx, next) => {
// 请求发送前
const {
// 请求配置
req,
// 此时为 null
res,
} = ctx;
// 调用 next 继续执行后续逻辑,最终发送请求
await next();
// 请求完成后
const {
// 请求配置
req,
// 服务端返回的响应体
res,
} = ctx;
};
```
## 全局中间件
可以添加全局中间件,对发送的每个请求生效。
```ts
import axios from 'axios-miniprogram';
// use 会返回 this可以链式添加多个
axios
.use(async (ctx, next) => {
console.log('1');
await next();
console.log('4');
})
.use(async (ctx, next) => {
console.log('2');
await next();
console.log('3');
});
// 洋葱模型执行顺序
// 1 -> 2 -> /test -> 3 -> 4
axios('/test');
```
## 实例中间件
可以为实例添加中间件,对实例发送的每个请求生效。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api.com',
});
instance.use(async (ctx, next) => {
console.log('instance request');
await next();
console.log('instance response');
});
// instance request -> https://api.com/test -> instance response
instance('https://api.com/test');
```
## 扩展实例中间件
可以为扩展实例添加中间件,扩展实例同时也可以复用父级中间件。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
axios.use(async (ctx, next) => {
console.log('axios request');
await next();
console.log('axios response');
});
const instance = axios.extend({
baseURL: '/test',
});
instance.use(async (ctx, next) => {
console.log('instance request');
await next();
console.log('instance response');
});
// 复用父级中间件
// axios request -> instance request -> https://api.com/test/user -> instance response -> axios response
instance('/user');
```

View File

@ -0,0 +1,115 @@
---
title: 请求拦截器
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于请求发送前拦截请求。
通常会用于转换请求配置,或实现一些自定义功能。
:::
## 添加请求拦截器
可以添加请求拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
```
也可以添加多个请求拦截器,后添加的会先执行。
```ts
import axios from 'axios-miniprogram';
// 先添加 后执行
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 后添加 先执行
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
```
## 移除请求拦截器
可以移除不再需要的请求拦截器。
```ts
import axios from 'axios-miniprogram';
const ejectId = axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 移除请求拦截器
axios.interceptors.request.eject(ejectId);
```
## 移除所有请求拦截器
可以移除所有请求拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 移除所有请求拦截器
axios.interceptors.request.clear();
```

View File

@ -0,0 +1,115 @@
---
title: 响应拦截器
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于 `response` 到达 `then` 之前,或 `error` 到达 `catch` 之前拦截响应。
通常会用于处理错误,但对于处理错误而言,使用 `errorHandler` 会是更好的选择。
:::
## 添加响应拦截器
可以添加响应拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
```
也可以添加多个响应拦截器,先添加的会先执行。
```ts
import axios from 'axios-miniprogram';
// 先添加 先执行
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 后添加 后执行
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
```
## 移除响应拦截器
可以移除不再需要的响应拦截器。
```ts
import axios from 'axios-miniprogram';
const ejectId = axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 移除响应拦截器
axios.interceptors.response.eject(ejectId);
```
## 移除所有响应拦截器
可以移除所有响应拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 移除所有响应拦截器
axios.interceptors.response.clear();
```

199
docs/pages/basics/config.md Normal file
View File

@ -0,0 +1,199 @@
---
title: 请求配置
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于自定义请求行为。
:::
## 通用配置项
可以设置这些配置项。
```ts
import axios from 'axios-miniprogram';
axios({
// 开发者服务器接口基础地址
baseURL: 'https://api.com',
// 开发者服务器接口地址
url: '/test',
// 请求方法
method: 'POST',
// 请求参数
params: {
id: 1,
},
// 请求数据
data: {
name: 'test',
},
// 请求头
headers: {
'Content-Type': 'application/json',
},
// 返回的数据格式
dataType: 'json',
// 响应的数据类型
responseType: 'text',
// 超时时间,单位为毫秒
timeout: 10000,
// 上传
upload: false,
// 下载
download: false,
// 请求参数系列化函数
paramsSerializer(params) {
console.log(params);
},
// 转换请求数据
transformRequest(data, headers) {
console.log(data);
},
// 转换响应数据
transformResponse(data, headers) {
console.log(data);
},
// 监听上传进度
onUploadProgress({ progress }) {
console.log(progress);
},
// 监听下载进度
onDownloadProgress({ progress }) {
console.log(progress);
},
// 校验状态码
validateStatus(status) {
console.log(status);
},
// 错误处理
errorHandler(error) {
console.log(error);
},
// 适配器
adapter(config) {
console.log(config);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 平台配置项
可以设置平台特有的配置项,具体情况取决于平台特性。
微信小程序示例:
```ts
import axios from 'axios-miniprogram';
axios({
// 开启 http2
enableHttp2: false,
// 开启 quic
enableQuic: false,
// 开启 cache
enableCache: false,
// 是否开启 HttpDNS 服务。如开启,需要同时填入 httpDNSServiceId 。
enableHttpDNS: false,
// HttpDNS 服务商 Id。
httpDNSServiceId: '123',
// 开启 transfer-encoding chunked。
enableChunked: false,
// wifi 下使用移动网络发送请求
forceCellularNetwork: false,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
想要了解更多请自行参阅对应平台文档。
## 自定义配置项
可以设置自定义配置项,从而实现一些自定义功能。
自定义配置项可以根据需要随意设置。
```ts
import axios from 'axios-miniprogram';
// 错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 显示错误信息
if (error.config.showError) {
wx.showToast({
title: error.response.data.errMsg,
});
}
}
};
// 请求拦截器
axios.interceptors.request.use((config) => {
// 自动显示 loading
if (config.showLoading) {
wx.showLoading();
}
return config;
});
// 响应拦截器
axios.interceptors.response.use((response) => {
// 自动隐藏 loading
if (response.config.showLoading) {
wx.hideLoading();
}
return response;
});
axios({
// 请求时自动 loading
showLoading: true,
// 出错时显示错误信息
showError: true,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```

View File

@ -0,0 +1,177 @@
---
title: 默认配置
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于设置作用于每个请求的配置项默认值。
[配置合并策略](/basics/defaults#配置合并策略)
:::
## 默认值
在不更改默认配置的情况下,它依然会存在一些默认值,在 [defaults.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/defaults.ts) 中定义,大概长下面这样。
```ts
{
// 适配器,在支持的平台中有值。
// 对于不支持平台而言,此值始终为 undefined需要您手动适配。
adapter: getDefaultAdapter(),
// 请求头
headers: {
// 通用请求头
common: {
Accept: 'application/json, text/plain, */*',
},
options: {}, // OPTIONS 方法请求头
get: {}, // GET 方法请求头
head: {}, // HEAD 方法请求头
post: {}, // POST 方法请求头
put: {}, // PUT 方法请求头
patch: {}, // PATCH 方法请求头
delete: {}, // DELETE 方法请求头
trace: {}, // TRACE 方法请求头
connect: {}, // CONNECT 方法请求头
},
// 校验状态码
validateStatus(status: number): boolean {
return status >= 200 && status < 300;
},
// 返回的数据格式
dataType: 'json',
// 响应的数据类型
responseType: 'text',
// 超时时长
timeout: 10000,
}
```
## 设置配置项
可以设置配置项默认值。
列举部分示例:
```ts
import axios from 'axios-miniprogram';
// 基础服务器地址
axios.defaults.baseURL = 'https://api.com';
// 通用请求头
axios.defaults.headers.common['Content-Type'] = 'application/json';
// POST 方法请求头
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded';
// 超时时间
axios.defaults.timeout = '60000';
// 校验状态码
axios.defaults.validateStatus = (status) => {
return status === 200;
};
// 错误处理
axios.defaults.errorHandler = (error) => {
console.log('出错了');
};
// 监听上传进度
axios.defaults.onUploadProgress = (event) => {
console.log('上传中:' + event.progress);
};
```
## 设置平台配置项
可以设置平台特有配置项默认值,具体情况取决于平台特性。
微信小程序示例:
```ts
import axios from 'axios-miniprogram';
// 开启 http2
axios.defaults.enableHttp2 = true;
// 开启 quic
axios.defaults.enableQuic = true;
// 开启 cache
axios.defaults.enableCache = true;
// 开启 HttpDNS 服务。
axios.defaults.enableHttpDNS = true;
// HttpDNS 服务商 Id。
axios.defaults.httpDNSServiceId = '123';
// wifi 下使用移动网络发送请求
axios.defaults.forceCellularNetwork = false;
```
想要了解更多请自行参阅对应平台文档。
## 设置自定义配置项
可以设置自定义配置项默认值。
```ts
import axios from 'axios-miniprogram';
// 出错时显示错误信息
axios.defaults.showError = true;
// 请求时自动 loading
axios.defaults.showLoading = true;
// 错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 显示错误信息
if (error.config.showError) {
wx.showToast({
title: error.response.data.errMsg,
});
}
}
};
// 请求拦截器
axios.interceptors.request.use((config) => {
// 自动显示 loading
if (config.showLoading) {
wx.showLoading();
}
return config;
});
// 响应拦截器
axios.interceptors.response.use((response) => {
// 自动隐藏 loading
if (response.config.showLoading) {
wx.hideLoading();
}
return response;
});
```
## 配置合并策略
默认配置和请求配置将会按优先级进行合并。
其中:
1. `url`、`method`、`data`、`upload`、`download` 只从 `config` 取值。
2. `headers`、`params` 会分别进行深度合并。
3. 其余属性则会优先从 `config` 取值。
具体配置合并策略请参阅 [mergeConfig.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/core/mergeConfig.ts) 。

View File

@ -0,0 +1,94 @@
---
title: 下载文件
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
下载文件资源到本地。
:::
::: warning 注意
下载文件只能使用 `GET` 方法请求,并将配置项 `download` 设置为 `true`
:::
## 普通的下载请求
可以下载文件资源到本地。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
})
.then((response) => {
const {
// 临时文件路径 (本地路径)。没传入 filePath 指定文件存储路径时会返回,下载后的文件会存储到一个临时文件
tempFilePath,
} = response.data;
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带参数的下载请求
可以指定文件下载后存储的路径 (本地路径)。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
params: {
filePath: '你的本地路径',
},
})
.then((response) => {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response.data;
})
.catch((error) => {
// 失败之后做些什么
});
```
## 监听下载进度
可以监听下载进度变化。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
params: {
filePath: '你的本地路径',
},
onDownloadProgress(event) {
const {
// 下载进度百分比
progress,
// 已经下载的数据长度,单位 Bytes
totalBytesWritten,
// 预预期需要下载的数据总长度,单位 Bytes
totalBytesExpectedToWrite,
} = event;
},
})
.then((response) => {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response.data;
})
.catch((error) => {
// 失败之后做些什么
});
```

View File

@ -0,0 +1,100 @@
---
title: 动态地址
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
简化地址参数的设置方式。
:::
## 设置请求参数
可以设置请求参数,最终会从请求参数中获取对应的值。
::: warning 注意
获取到值后会从请求参数中删除对应的值。
:::
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
// 获取到 id 之后,会从 params 中删除 id
axios('https://api.com/:id', {
params: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 设置请求数据
可以设置请求数据,最终会从请求数据中获取对应的值。
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
// 获取到 id 之后,不会从 data 中删除 id
axios('https://api.com/:id', {
method: 'POST',
data: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 同时设置请求参数和请求数据
可以同时设置请求参数和请求数据,会优先从请求参数中获取对应的值。
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
axios('https://api.com/:id', {
method: 'POST',
params: {
id: 1,
},
data: {
id: 2,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 请求的服务端地址 https://api.com/1/test
axios('https://api.com/:id/:name', {
method: 'POST',
params: {
id: 1,
},
data: {
name: 'test',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```

View File

@ -0,0 +1,162 @@
---
title: 错误处理
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
当请求失败时,可以对错误进行处理。
:::
## 校验状态抛出错误
可以设置校验状态,自定义抛出错误的状态码。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
validateStatus(status) {
return status === 200;
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 用 `catch` 处理错误
可以处理不同类型的错误。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
if (axios.isAxiosError(error)) {
// 响应错误
const {
// 错误消息
message,
// 请求配置
config,
// 请求任务,也就是请求函数返回的结果
request,
// 响应体
response,
} = error;
if (response.isFail) {
// 平台或适配器错误
} else {
// 使用 `validateStatus` 自定义抛出的错误
}
} else if (axios.isCancel(error)) {
// 取消请求
} else {
// 其他错误
}
return Promise.reject(error);
});
```
## 用 `errorHandler` 处理错误
可以使用 `errorHandler` 处理不同类型的错误。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
errorHandler(error) {
if (axios.isAxiosError(error)) {
// 响应错误
const {
// 错误消息
message,
// 请求配置
config,
// 请求任务,也就是请求函数返回的结果
request,
// 响应体
response,
} = error;
if (response.isFail) {
// 平台或适配器错误
} else {
// 使用 `validateStatus` 自定义抛出的错误
}
} else if (axios.isCancel(error)) {
// 取消请求
} else {
// 其他错误
}
return Promise.reject(error);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 全局错误处理
可以设置全局错误处理,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
// 全局错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 响应错误
const {
// 错误消息
message,
// 请求配置
config,
// 请求任务,也就是请求函数返回的结果
request,
// 响应体
response,
} = error;
if (response.isFail) {
// 平台或适配器错误
} else {
// 使用 `validateStatus` 自定义抛出的错误
}
} else if (axios.isCancel(error)) {
// 取消请求
} else {
// 其他错误
}
return Promise.reject(error);
};
```

View File

@ -0,0 +1,33 @@
---
title: 参数系列化
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
支持自定义参数系列化器。
:::
## 自定义参数系列化器
可以用自己的方式系列化参数。
```ts
import axios from 'axios-miniprogram';
import qs from 'qs';
axios('https://api.com', {
params: {
id: 1,
},
paramsSerializer(params) {
return qs.stringify(params);
},
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```

View File

@ -0,0 +1,91 @@
---
title: 发送请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
发送任意请求方法的 HTTP 请求。
:::
## 基础用法
可以直接传递 `url` 发送请求,默认发送的是 `GET` 方法请求。
```ts
import axios from 'axios-miniprogram';
axios
.request('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置
可以额外传递第二个参数 `config`,用于指定请求方法以及其他配置项。
```ts
import axios from 'axios-miniprogram';
axios
.request('https://api.com/test', {
method: 'POST', // 此时会发送 POST 方法请求
data: {
name: 'test',
password: '123456',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 仅有请求配置
可以直接传递 `config` 发送请求。
```ts
import axios from 'axios-miniprogram';
axios
.request({
url: 'https://api.com/test/:id',
params: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 请求方法
提供一系列基于 `axios.request()` 的请求方法,可以使用请求方法简化请求。
- [axios.options(url, config?)](/method/OPTIONS)
- [axios.get(url, params?, config?)](/method/GET)
- [axios.head(url, params?, config?)](/method/HEAD)
- [axios.post(url, data?, config?)](/method/POST)
- [axios.put(url, data?, config?)](/method/PUT)
- [axios.patch(url, data?, config?)](/method/PATCH)
- [axios.delete(url, params?, config?)](/method/DELETE)
- [axios.trace(url, config?)](/method/TRACE)
- [axios.connect(url, config?)](/method/CONNECT)
## 说明
您可能发现 `axios.request()``axios()` 使用方式完全一致,为什么用法是一样的?
其实它们本就是同一个请求函数,`axios` 是基于 `axios.request` 添加了一系列工具函数改造而来,其目的是为了简化使用。

View File

@ -0,0 +1,69 @@
---
title: 响应体
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
`response` 是响应正文。返回的数据类型为 `String/Object/ArrayBuffer`。这取决于请求配置的 `responseType` 属性。
:::
## 通用属性
请求成功返回的 `response` 带有这些属性。
```ts
import axios from 'axios-miniprogram';
axios('https//api.com')
.then((response) => {
const {
// 开发者服务器返回的 HTTP 状态码
status,
// 状态文本
statusText,
// 开发者服务器返回的数据
data,
// 开发者服务器返回的响应头
headers,
// 请求配置
config,
// 请求任务
request,
} = response;
})
.catch((error) => {
// 失败之后做些什么
});
```
## 平台属性
请求成功返回的 `response` 可能带有平台特有的属性,具体情况取决于平台特性。
微信小程序示例:
```ts
import axios from 'axios-miniprogram';
axios('https://api.com')
.then((response) => {
const {
// 开发者服务器返回的 cookies格式为字符串数组
cookies,
// 网络请求过程中一些调试信息
profile,
} = response;
})
.catch((error) => {
// 失败之后做些什么
});
```
想要了解更多请自行参阅对应平台文档。

View File

@ -0,0 +1,121 @@
---
title: 转换数据
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
请求发送前转换请求数据,响应到达 `then` 之前转换响应数据。
:::
## 转换请求数据
可以转换请求数据,只对允许携带请求数据的请求方法生效,允许携带请求数据的方法有:`POST`、`PUT`、`PATCH`。
```ts
import axios from 'axios-miniprogram';
axios('test', {
method: 'POST',
transformRequest(data, headers) {
return JSON.stringify(data);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
也支持多次转换。
```ts
import axios from 'axios-miniprogram';
axios('test', {
method: 'POST',
transformRequest: [
(data, headers) => {
return JSON.stringify(data);
},
(data, headers) => {
return encodeURIComponent(data);
},
],
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 全局转换请求数据
可以设置全局转换请求数据,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
axios.defaults.transformRequest = (data, headers) => {
return JSON.stringify(data);
};
```
## 转换响应数据
可以转换响应数据。
```ts
import axios from 'axios-miniprogram';
axios('test', {
transformResponse(data, headers) {
return JSON.parse(data);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
也支持多次转换。
```ts
import axios from 'axios-miniprogram';
axios('test', {
transformResponse: [
(data, headers) => {
return decodeURIComponent(data);
},
(data, headers) => {
return JSON.parse(data);
},
],
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 全局转换响应数据
可以设置全局转换响应数据,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
axios.defaults.transformResponse = (data, headers) => {
return JSON.parse(data);
};
```

124
docs/pages/basics/upload.md Normal file
View File

@ -0,0 +1,124 @@
---
title: 上传文件
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
将本地资源上传到服务器。
:::
::: warning 注意
上传文件只能使用 `POST` 方法请求,并将请求配置项 `upload` 设置为 `true`
:::
## 普通的上传请求
可以将本地资源上传到服务器。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
},
})
.then((response) => {
const {
// 开发者服务器返回的数据
data,
} = response;
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带 `formData` 的上传请求
也可以携带额外的 `formData` 发送给服务端。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
user: '123',
},
})
.then((response) => {
const {
// 开发者服务器返回的数据
data,
} = response;
})
.catch((error) => {
// 失败之后做些什么
});
```
## 监听上传进度
也可以监听上传进度变化。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
user: '123',
},
onUploadProgress(event) {
const {
// 上传进度百分比
progress,
// 已经上传的数据长度,单位 Bytes
totalBytesSent,
// 预期需要上传的数据总长度,单位 Bytes
totalBytesExpectedToSend,
} = event;
},
})
.then((response) => {
const {
// 开发者服务器返回的数据
data,
} = response;
})
.catch((error) => {
// 失败之后做些什么
});
```

View File

@ -0,0 +1,187 @@
---
title: 开始
---
# {{ $frontmatter.title }}
## 安装
:::: code-group
```bash [NPM]
$ npm install axios-miniprogram
```
```bash [YARN]
$ yarn add axios-miniprogram
```
```bash [PNPM]
$ pnpm install axios-miniprogram
```
::::
原生小程序也可以直接[下载源码包](https://github.com/zjxxxxxxxxx/axios-miniprogram/releases),但是这样是失去类型提示和 `sourceMap` 定位功能。
建议在条件允许的情况下优先使用包管理工具安装的方式,而不是使用下载源码包的方式。
## 引用
可以在不同的模块系统导入需要用到的功能。
:::: code-group
```ts [ES Module]
import axios, {
// 取消令牌
CancelToken,
// 判断取消请求错误
isCancel,
// 原始 Axios 类
Axios,
// 判断请求响应错误
isAxiosError,
// 创建平台适配器
createAdapter,
} from 'axios-miniprogram';
axios('/test');
```
```ts [CommonJS]
const {
// 静态对象
// 注意:默认导出的 axios 在 CommonJS 里是以 default 属性的方式存在
default: axios,
// 取消令牌
CancelToken,
// 判断取消请求错误
isCancel,
// 原始 Axios 类
Axios,
// 判断请求响应错误
isAxiosError,
// 创建平台适配器
createAdapter,
} = require('axios-miniprogram');
axios('/test');
```
::::
不同的模块系统存在一些小差异,`esm` 会自动处理默认导入,但 `cjs` 不会处理默认导入。
```ts
// 默认导入esm 和 cjs 这两种写法是等价关系
import axios from 'axios-miniprogram';
const axios = require('axios-miniprogram').default;
// 别名导入esm 和 cjs 这两种写法是等价关系
import * as axios from 'axios-miniprogram';
const axios = require('axios-miniprogram');
// 具名导入esm 和 cjs 这两种写法是等价关系
import {
default as axios,
CancelToken,
isCancel,
Axios,
isAxiosError,
createAdapter,
} from 'axios-miniprogram';
const {
default: axios,
CancelToken,
isCancel,
Axios,
isAxiosError,
createAdapter,
} = require('axios-miniprogram');
```
## 使用
### `axios(url, config?)`
可以通过把 `url``config` 传递给 `axios` 来发送请求。
注意: `config` 为选填
```ts
import axios from 'axios-miniprogram';
// 默认发送 GET 请求
axios('https://api.com/test')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
// 发送 POST 请求
axios('https://api.com/test', {
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
### `axios(config)`
也可以直接把 `config` 传递给 `axios` 来发送请求。
```ts
import axios from 'axios-miniprogram';
// 默认发送 GET 请求
axios({
url: 'https://api.com/test',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
// 发送 POST 请求
axios({
url: 'https://api.com/test',
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
也可以使用请求方法简化请求。
- [axios.request(url, config?) | axios.request(config)](/basics/request)
- [axios.options(url, config?)](/method/OPTIONS)
- [axios.get(url, params?, config?)](/method/GET)
- [axios.head(url, params?, config?)](/method/HEAD)
- [axios.post(url, data?, config?)](/method/POST)
- [axios.put(url, data?, config?)](/method/PUT)
- [axios.patch(url, data?, config?)](/method/PATCH)
- [axios.delete(url, params?, config?)](/method/DELETE)
- [axios.trace(url, config?)](/method/TRACE)
- [axios.connect(url, config?)](/method/CONNECT)

30
docs/pages/index.md Normal file
View File

@ -0,0 +1,30 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: 'axios-miniprogram'
text: '基于 Promise 的 HTTP 请求库,适用于各大小程序平台。'
tagline: 通用小程序请求库
actions:
- theme: alt
text: 简介
link: /guide/intro
- theme: brand
text: 快速开始
link: /guide/quick-start
features:
- title: 节省空间
details: 包尺寸仅 10 kb不会占用您太多空间
icon: 🤌
- title: 简单易用
details: 提供了简易的 API并且具有很强的可拓展性
icon: 🎯
- title: 方便快捷
details: 除了提供 npm 安装包以外,还为原生小程序提供开箱即用的源码包
icon: 📦
- title: 跨平台
details: 我很全能,所有小程序平台都可以兼容
icon: 🎭
---

View File

@ -0,0 +1,51 @@
---
title: CONNECT 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
在 HTTP 协议中CONNECT 方法可以开启一个客户端与所请求资源之间的双向沟通的通道。它可以用来创建隧道tunnel
:::
## 普通的 `CONNECT` 请求
可以传递第一个参数 `url` 发送 `CONNECT` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.connect('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `CONNECT` 请求
也可以额外传递第二个参数 `config` 发送携带请求配置的 `CONNECT` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.connect('https://api.com/test', {
headers: {
Connection: 'Keep-Alive',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx swan='仅 Android 支持' tt='1.0.0' qq />

View File

@ -0,0 +1,76 @@
---
title: DELETE 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP DELETE 请求方法用于删除指定的资源。
:::
## 普通的 `DELETE` 请求
可以传递第一个参数 `url` 发送 `DELETE` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.delete('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带参数的 `DELETE` 请求
也可以额外传递第二个参数 `params` 发送携带参数的 `DELETE` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.delete('https://api.com/test/:id', {
id: 1,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `DELETE` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `DELETE` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.delete(
'https://api.com/test/:id',
{
id: 1,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx my swan tt='1.0.0' qq tt2 qh />

76
docs/pages/method/GET.md Normal file
View File

@ -0,0 +1,76 @@
---
title: GET 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP GET 方法请求指定的资源。使用 GET 的请求应该只用于获取数据。
:::
## 普通的 `GET` 请求
可以传递第一个参数 `url` 发送 `GET` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.get('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带参数的 `GET` 请求
也可以额外传递第二个参数 `params` 发送携带参数的 `GET` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.get('https://api.com/test/:id', {
id: 1,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `GET` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `GET` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.get(
'https://api.com/test/:id',
{
id: 1,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx my swan jd tt='1.0.0' qq dd tt2 ks qh />

76
docs/pages/method/HEAD.md Normal file
View File

@ -0,0 +1,76 @@
---
title: HEAD 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP HEAD 方法请求资源的头部信息,并且这些头部与 HTTP GET 方法请求时返回的一致。该请求方法的一个使用场景是在下载一个大文件前先获取其大小再决定是否要下载,以此可以节约带宽资源。
:::
## 普通的 `HEAD` 请求
可以传递第一个参数 `url` 发送 `HEAD` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.head('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带参数的 `HEAD` 请求
也可以额外传递第二个参数 `params` 发送携带参数的 `HEAD` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.head('https://api.com/test/:id', {
id: 1,
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `HEAD` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `HEAD` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.head(
'https://api.com/test/:id',
{
id: 1,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx swan tt='1.0.0' qq tt2 qh />

View File

@ -0,0 +1,51 @@
---
title: OPTIONS 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP OPTIONS 方法用于获取目的资源所支持的通信选项。客户端可以对特定的 URL 使用 OPTIONS 方法,也可以对整站(通过将 URL 设置为“\*”)使用该方法。
:::
## 普通的 `OPTIONS` 请求
可以传递第一个参数 `url` 发送 `OPTIONS` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.options('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `OPTIONS` 请求
也可以额外传递第二个参数 `config` 发送携带请求配置的 `OPTIONS` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.options('https://api.com/test', {
headers: {
Accept: '*/*',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx swan tt='1.0.0' qq tt2 qh />

View File

@ -0,0 +1,80 @@
---
title: PATCH 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
在 HTTP 协议中,请求方法 PATCH 用于对资源进行部分修改。
在 HTTP 协议中, PUT 方法已经被用来表示对资源进行整体覆盖,而 POST 方法则没有对标准的补丁格式的提供支持。不同于 PUT 方法,而与 POST 方法类似PATCH 方法是非幂等的,这就意味着连续多个相同的请求会产生不同的效果。
:::
## 普通的 `PATCH` 请求
可以传递第一个参数 `url` 发送 `PATCH` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.patch('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带数据的 `PATCH` 请求
也可以额外传递第二个参数 `data` 发送携带数据的 `PATCH` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.patch('https://api.com/test/:id', {
id: 1,
name: 'test',
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `PATCH` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `PATCH` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.patch(
'https://api.com/test/:id',
{
id: 1,
name: 'test',
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility tt='2.42.0' />

78
docs/pages/method/POST.md Normal file
View File

@ -0,0 +1,78 @@
---
title: POST 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP POST 方法发送数据给服务器。请求主体的类型由 Content-Type 首部指定。
:::
## 普通的 `POST` 请求
可以传递第一个参数 `url` 发送 `POST` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.post('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带数据的 `POST` 请求
也可以额外传递第二个参数 `data` 发送携带数据的 `POST` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.post('https://api.com/test', {
name: 'test',
password: '123456',
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `POST` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `POST` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.post(
'https://api.com/test',
{
name: 'test',
password: '123456',
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx my swan jd tt='1.0.0' qq dd tt2 ks qh />

80
docs/pages/method/PUT.md Normal file
View File

@ -0,0 +1,80 @@
---
title: PUT 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP PUT 请求方法使用请求中的数据创建或者替换目标资源。
:::
## 普通的 `PUT` 请求
可以传递第一个参数 `url` 发送 `PUT` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.put('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带数据的 `PUT` 请求
也可以额外传递第二个参数 `data` 发送携带数据的 `PUT` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.put('https://api.com/test/:id', {
id: 1,
name: 'test',
password: '123456',
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `PUT` 请求
也可以额外传递第三个参数 `config` 发送携带请求配置的 `PUT` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.put(
'https://api.com/test/:id',
{
id: 1,
name: 'test',
password: '123456',
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx my swan tt='1.0.0' qq tt2 qh />

View File

@ -0,0 +1,51 @@
---
title: TRACE 请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
HTTP TRACE 方法实现沿通向目标资源的路径的消息环回loop-back测试提供了一种实用的 debug 机制。
:::
## 普通的 `TRACE` 请求
可以传递第一个参数 `url` 发送 `TRACE` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.trace('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 携带请求配置的 `TRACE` 请求
也可以额外传递第二个参数 `config` 发送携带请求配置的 `TRACE` 请求。
```ts
import axios from 'axios-miniprogram';
axios
.trace('https://api.com/test', {
headers: {
'Content-Type': 'message/http',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 兼容性
<VPCompatibility wx swan='仅 Android 支持' tt='1.0.0' qq />

View File

@ -7,20 +7,21 @@
"lib": ["DOM", "ESNext"],
"strict": true,
"jsx": "preserve",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"noUnusedLocals": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"types": ["vite/client", "vite-plugin-pwa/client", "vitepress"]
"isolatedModules": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./.vitepress/**/*.ts",
"./.vitepress/**/*.vue",
"./.vitepress/components.d.ts",
"./global.d.ts",
"../global.d.ts"
],
"exclude": ["dist", "node_modules"]
"exclude": ["node_modules"]
}

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>

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