├── demo ├── miniprograme-native │ ├── app.wxss │ ├── index │ │ ├── index.json │ │ ├── index.wxss │ │ ├── index.wxml │ │ └── index.js │ ├── app.js │ ├── app.json │ ├── package.json │ ├── project.config.json │ ├── miniprogram_npm │ │ ├── is-buffer │ │ │ ├── index.js.map │ │ │ └── index.js │ │ ├── ms │ │ │ ├── index.js.map │ │ │ └── index.js │ │ ├── axios-miniprogram-adapter │ │ │ └── index.js │ │ ├── follow-redirects │ │ │ ├── index.js.map │ │ │ └── index.js │ │ └── debug │ │ │ ├── index.js.map │ │ │ └── index.js │ └── package-lock.json ├── alipay-demo │ ├── pages │ │ └── index │ │ │ ├── index.json │ │ │ ├── index.acss │ │ │ ├── index.axml │ │ │ └── index.js │ ├── app.acss │ ├── snapshot.png │ ├── app.json │ ├── app.js │ ├── package.json │ └── package-lock.json └── miniprograme-example-megalo │ ├── .eslintignore │ ├── .env.development │ ├── .env.production │ ├── .gitignore │ ├── .eslintrc.js │ ├── src │ ├── App.vue │ ├── utils │ │ └── platform.js │ ├── index.js │ ├── components │ │ └── HelloWorld.vue │ └── pages │ │ ├── search-tip.vue │ │ └── index.vue │ ├── megalo.config.js │ ├── README.md │ └── package.json ├── .gitignore ├── doc ├── alipay.png ├── baidu.png ├── wechat.png ├── dingding.png ├── example.png └── api.md ├── .travis.yml ├── index.d.ts ├── .vscode └── settings.json ├── CHANGELOG.md ├── .editorconfig ├── .npmignore ├── .github └── ISSUE_TEMPLATE ├── TODO.md ├── config ├── .eslintrc.js ├── rollup.config.esm.js ├── rollup.config.aio.js ├── rollup.config.js └── rollup.js ├── types └── index.d.ts ├── test ├── wx-env-fake.js ├── specs │ └── wxAdapter.spec.js ├── browser │ └── index.html └── test.js ├── tsconfig.json ├── src ├── utils │ ├── encoder.ts │ └── platForm.ts └── index.ts ├── LICENSE ├── package.json ├── README.md └── dist ├── index.esm.js ├── index.js ├── index.aio.js └── miniprogram └── index.js /demo/miniprograme-native/app.wxss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /demo/alipay-demo/pages/index/index.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /demo/miniprograme-native/index/index.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .rpt2_cache 3 | rename.js 4 | -------------------------------------------------------------------------------- /demo/alipay-demo/app.acss: -------------------------------------------------------------------------------- 1 | page { 2 | background: #f7f7f7; 3 | } 4 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist-* 3 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/.env.development: -------------------------------------------------------------------------------- 1 | VUE_APP_TEST=我是development模式的环境变量 -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/.env.production: -------------------------------------------------------------------------------- 1 | VUE_APP_TEST=我是production模式的环境变量 -------------------------------------------------------------------------------- /demo/miniprograme-native/app.js: -------------------------------------------------------------------------------- 1 | App({ 2 | onLaunch: function () { 3 | 4 | } 5 | }) 6 | -------------------------------------------------------------------------------- /doc/alipay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/doc/alipay.png -------------------------------------------------------------------------------- /doc/baidu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/doc/baidu.png -------------------------------------------------------------------------------- /doc/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/doc/wechat.png -------------------------------------------------------------------------------- /demo/miniprograme-native/index/index.wxss: -------------------------------------------------------------------------------- 1 | .intro { 2 | margin: 30px; 3 | text-align: center; 4 | } -------------------------------------------------------------------------------- /doc/dingding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/doc/dingding.png -------------------------------------------------------------------------------- /doc/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/doc/example.png -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "8" 4 | - "10" 5 | script: 6 | - npm run build 7 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist* 3 | .DS_Store 4 | .idea 5 | .vscode 6 | package-lock.json -------------------------------------------------------------------------------- /demo/alipay-demo/snapshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigmeow/axios-miniprogram-adapter/HEAD/demo/alipay-demo/snapshot.png -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: [ 4 | '@megalo/standard' 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /demo/alipay-demo/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "pages": [ 3 | "pages/index/index" 4 | ], 5 | "window": { 6 | "defaultTitle": "Axios 能力测试" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { AxiosRequestConfig, AxiosPromise } from 'axios'; 2 | export default function mpAdapter(config: AxiosRequestConfig): AxiosPromise; 3 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "eslint.validate": [ 3 | "javascript", 4 | "html" 5 | ], 6 | "editor.codeActionsOnSave": { 7 | "source.fixAll.eslint": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 变更日志 2 | 3 | ## 0.1.0 / 2018-11-14 4 | 5 | - 支持在小程序中使用axios 6 | 7 | 8 | ## 0.3.1 / 2020-07-07 9 | 10 | - fix: 修复在支付宝中 headers 设置无效的bug 11 | - change: 默认打包成 commonJs 模块 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | config 3 | demo 4 | src 5 | test 6 | .editorconfig 7 | .travis.yml 8 | CHANGELOG.md 9 | package-lock.json 10 | TODO.md 11 | rename.js 12 | .rpt2_cache 13 | .npmignore 14 | types 15 | -------------------------------------------------------------------------------- /demo/alipay-demo/pages/index/index.acss: -------------------------------------------------------------------------------- 1 | .btn { 2 | display: block; 3 | width: 80%; 4 | margin: 10px auto; 5 | border-radius: 8px; 6 | height: 40px; 7 | display: flex; 8 | align-items: center; 9 | justify-content: center; 10 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | ### 问题是什么 2 | 问题的具体描述,尽量详细 3 | 4 | ### 环境 5 | - 手机: (例如小米6) 6 | - 系统:(例如安卓7.1.1) 7 | - 微信版本:xxx 8 | - axios-miniprogram-adapter版本:xxx 9 | - 其他版本信息 10 | 11 | ### 在线例子 12 | 尽可能提供在线例子 13 | 14 | ### 报错信息 15 | 可贴图或者报错代码 16 | -------------------------------------------------------------------------------- /demo/alipay-demo/app.js: -------------------------------------------------------------------------------- 1 | App({ 2 | onLaunch(options) { 3 | // 第一次打开 4 | // options.query == {number:1} 5 | console.info('App onLaunch'); 6 | }, 7 | onShow(options) { 8 | // 从后台被 scheme 重新打开 9 | // options.query == {number:1} 10 | }, 11 | }); 12 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # 计划列表 2 | 这里列出会在未来添加的新功能,和已经完成的功能 3 | 4 | - [X] 在微信小程序中使用axios 5 | - [X] 支持支付宝、百度小程序 6 | 7 | [✘] 小程序中迸发请求上限最高是10条,需要做请求队列(从微信基础库版本```v1.4.0 (2017.07.10)```后微信官方已经内部支持请求队列,超出10条后走队列) 8 | 详情可[点击](https://developers.weixin.qq.com/miniprogram/dev/framework/release/v1.html)这里查看 9 | -------------------------------------------------------------------------------- /demo/miniprograme-native/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "pages":[ 3 | "index/index" 4 | ], 5 | "window":{ 6 | "backgroundTextStyle":"light", 7 | "navigationBarBackgroundColor": "#fff", 8 | "navigationBarTitleText": "WeChat", 9 | "navigationBarTextStyle":"black" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/App.vue: -------------------------------------------------------------------------------- 1 | 2 | 11 | -------------------------------------------------------------------------------- /config/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'env': { 3 | 'node': true 4 | }, 5 | 'extends': [ 6 | 'plugin:vue/essential', 7 | '@vue/standard', 8 | '@vue/typescript' 9 | ], 10 | 'parserOptions': { 11 | 'sourceType': 'module' 12 | }, 13 | 'rules': { 14 | 'no-console': 0 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/utils/platform.js: -------------------------------------------------------------------------------- 1 | function getPlatForm () { 2 | switch (true) { 3 | case typeof wx === 'object': 4 | return wx 5 | case typeof swan === 'object': 6 | return swan 7 | case typeof my === 'object': 8 | return my 9 | default: 10 | return wx 11 | } 12 | } 13 | export default getPlatForm() 14 | -------------------------------------------------------------------------------- /demo/alipay-demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alipay-axios-demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "axios": "^0.19.2", 13 | "axios-miniprogram-adapter": "^0.3.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/megalo.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | chainWebpack: chainConfig => { 3 | 4 | chainConfig.resolve.aliasFields.add('browser') 5 | // console.log('chainWebpack执行了', chainConfig.toString()) 6 | }, 7 | 8 | css: { 9 | loaderOptions: { 10 | // https://github.com/megalojs/megalo-px2rpx-loader 11 | px2rpx: false 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /demo/miniprograme-native/index/index.wxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo/miniprograme-native/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "miniprograme-native", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "axios": "^0.18.1", 13 | "axios-miniprogram-adapter": "https://github.com/bigmeow/axios-miniprogram-adapter.git" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | interface MpResponse extends WechatMiniprogram.RequestSuccessCallbackResult { 2 | /** 支付宝、钉钉独有 */ 3 | headers: WechatMiniprogram.IAnyObject, 4 | status: number 5 | } 6 | 7 | interface MpRequestConfig extends WechatMiniprogram.RequestOption { 8 | /** 仅支付宝、钉钉小程序独有 */ 9 | headers?: WechatMiniprogram.IAnyObject 10 | } 11 | 12 | declare let swan: any 13 | 14 | declare let my: any 15 | 16 | declare let dd: any -------------------------------------------------------------------------------- /config/rollup.config.esm.js: -------------------------------------------------------------------------------- 1 | import common from './rollup' 2 | 3 | export default { 4 | input: 'src/index.ts', 5 | output: { 6 | file: 'dist/index.esm.js', 7 | format: 'es', 8 | // When export and export default are not used at the same time, set legacy to true. 9 | // legacy: true, 10 | banner: common.banner 11 | }, 12 | // legacy: true, 13 | 14 | external: common.external, 15 | plugins: [ 16 | common.getCompiler() 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/index.js: -------------------------------------------------------------------------------- 1 | import App from '.' 2 | import Vue from 'vue' 3 | 4 | const app = new Vue(App) 5 | 6 | app.$mount() 7 | 8 | export default { 9 | config: { 10 | // pages 的首个页面会被编译成首页 11 | pages: [ 12 | 'pages/index', 13 | 'pages/search-tip' 14 | ], 15 | window: { 16 | backgroundTextStyle: 'light', 17 | navigationBarBackgroundColor: '#fff', 18 | navigationBarTitleText: 'axios测试', 19 | navigationBarTextStyle: 'black' 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/README.md: -------------------------------------------------------------------------------- 1 | ## megalo-demo 2 | 3 | megalo demo 工程,支持微信小程序和支付宝小程序,在逐步完善中。 4 | 5 | ## 运行 6 | 7 | 微信小程序版本: 8 | 9 | ```bash 10 | npm run dev:wechat 11 | ``` 12 | 13 | 支付宝小程序版本: 14 | 15 | ```bash 16 | npm run dev:alipay 17 | ``` 18 | 19 | 百度智能小程序版本: 20 | 21 | ```bash 22 | npm run dev:swan 23 | ``` 24 | ## 注意,demo里请求用到了下列域名,如需在真机上运行,请将其加入安全域名设置 25 | - suggest.taobao.com 26 | - api.github.com 27 | - easy-mock.com 28 | 29 | ## issue 30 | 31 | demo 工程有问题,请到 [这里](https://github.com/megalojs/megalo-cli) 提 issue,便于管理,谢谢。 32 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/components/HelloWorld.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 21 | 22 | 23 | 29 | -------------------------------------------------------------------------------- /test/wx-env-fake.js: -------------------------------------------------------------------------------- 1 | const mockSuccessData = { 2 | data: { 'name': 'lizong' }, 3 | statusCode: 200, 4 | header: { 5 | 'Access-Control-Allow-Credentials': 'true', 6 | 'Access-Control-Allow-Origin': 'http://127.0.0.1:18624', 7 | 'Connection': 'keep-alive', 8 | 'Content-Length': '52', 9 | 'Content-Type': 'application/json; charset=utf-8' 10 | } 11 | } 12 | const wx = { 13 | request: function (option) { 14 | console.log(option) 15 | setTimeout(() => { 16 | option.success && option.success(mockSuccessData) 17 | option.complete && option.complete({ a: 1 }) 18 | }, 1000) 19 | } 20 | } 21 | module.exports = wx 22 | -------------------------------------------------------------------------------- /test/specs/wxAdapter.spec.js: -------------------------------------------------------------------------------- 1 | const expect = require('expect.js'); 2 | const axios = require('axios'); 3 | const mpAdapter = require('../../dist/index.js'); 4 | 5 | describe('Adapter', function() { 6 | 7 | it('should support 微信小程序 adapter', function(done) { 8 | let called = false 9 | global.wx = { 10 | request: function (options) { 11 | called = true 12 | } 13 | } 14 | axios.defaults.adapter = mpAdapter 15 | axios.get('https://api.github.com/users/mzabriskie') 16 | setTimeout(() => { 17 | expect(called).to.equal(true); 18 | done() 19 | }, 100) 20 | }) 21 | 22 | after(() => { 23 | global.wx = undefined 24 | }) 25 | }) 26 | -------------------------------------------------------------------------------- /config/rollup.config.aio.js: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | 3 | import common from './rollup' 4 | import nodeResolve from '@rollup/plugin-node-resolve' 5 | import commonjs from '@rollup/plugin-commonjs' 6 | 7 | export default { 8 | input: 'src/index.ts', 9 | output: { 10 | file: 'dist/index.aio.js', 11 | format: 'umd', 12 | // 如果不同时使用 export 与 export default 可打开legacy 13 | // legacy: true, 14 | name: common.name, 15 | banner: common.banner 16 | }, 17 | external: common.external, 18 | plugins: [ 19 | nodeResolve({ 20 | main: true, 21 | extensions: ['.ts', '.js'] 22 | }), 23 | commonjs({ 24 | include: 'node_modules/**' 25 | }), 26 | common.getCompiler() 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /demo/alipay-demo/pages/index/index.axml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 注意打开调试工具,查看console 和 network来测试 4 | 7 | 8 | 11 | 12 | 15 | 16 | 19 | 20 | 23 | 24 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "esnext", 5 | "lib": [ 6 | "es2017", 7 | "es2015", 8 | "es2015.promise" 9 | ], 10 | "strict": true, 11 | "noImplicitAny": false, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": false, 14 | "moduleResolution": "node", 15 | "importHelpers": true, 16 | "strictPropertyInitialization": false, 17 | "baseUrl": ".", 18 | "types": [ 19 | "node", 20 | "miniprogram-api-typings" 21 | ], 22 | "allowSyntheticDefaultImports": true, 23 | "experimentalDecorators": true, 24 | "emitDecoratorMetadata": true 25 | }, 26 | "include": [ 27 | "./src/**/*.ts", 28 | "./types/**/*.ts" 29 | ], 30 | "exclude": [ 31 | "node_modules" 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /demo/miniprograme-native/project.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "description": "项目配置文件", 3 | "packOptions": { 4 | "ignore": [] 5 | }, 6 | "setting": { 7 | "urlCheck": false, 8 | "es6": true, 9 | "postcss": true, 10 | "minified": true, 11 | "newFeature": true, 12 | "nodeModules": true, 13 | "autoAudits": false 14 | }, 15 | "compileType": "miniprogram", 16 | "libVersion": "2.2.1", 17 | "appid": "wx74aab0bf029f10b5", 18 | "projectname": "%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91%E8%80%85%E5%B7%A5%E5%85%B7%E4%B8%AD%E4%BD%BF%E7%94%A8axios", 19 | "debugOptions": { 20 | "hidedInDevtools": [] 21 | }, 22 | "isGameTourist": false, 23 | "condition": { 24 | "search": { 25 | "current": -1, 26 | "list": [] 27 | }, 28 | "conversation": { 29 | "current": -1, 30 | "list": [] 31 | }, 32 | "game": { 33 | "currentL": -1, 34 | "list": [] 35 | }, 36 | "miniprogram": { 37 | "current": -1, 38 | "list": [] 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/utils/encoder.ts: -------------------------------------------------------------------------------- 1 | const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' 2 | // encoder 3 | function encoder (input) { 4 | const str = String(input) 5 | // initialize result and counter 6 | let block; let charCode; let idx = 0; let map = chars; let output = '' 7 | for ( 8 | ; 9 | // if the next str index does not exist: 10 | // change the mapping table to "=" 11 | // check if d has no fractional digits 12 | str.charAt(idx | 0) || (map = '=', idx % 1); 13 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 14 | output += map.charAt(63 & block >> 8 - idx % 1 * 8) 15 | ) { 16 | charCode = str.charCodeAt(idx += 3 / 4) 17 | if (charCode > 0xFF) { 18 | throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.") 19 | } 20 | block = block << 8 | charCode 21 | } 22 | return output 23 | } 24 | 25 | export default encoder 26 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/is-buffer/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["index.js"],"names":[],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"index.js","sourcesContent":["/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n"]} -------------------------------------------------------------------------------- /config/rollup.config.js: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | 3 | import common from './rollup' 4 | import nodeResolve from '@rollup/plugin-node-resolve' 5 | import commonjs from '@rollup/plugin-commonjs' 6 | 7 | const isProd = process.env.NODE_ENV === 'production' 8 | export default { 9 | input: 'src/index.ts', 10 | output: { 11 | file: isProd ? 'dist/miniprogram/index.js' : 'dist/index.js', 12 | format: 'cjs', 13 | // 如果不同时使用 export 与 export default 可打开legacy 14 | // legacy: true, 15 | banner: common.banner 16 | // sourcemap: isProd 17 | }, 18 | // 小程序不支持包内require别的包,必须把别的包也一起打包进来 19 | external: isProd ? [] : common.external, 20 | plugins: [ 21 | nodeResolve({ 22 | main: true, 23 | extensions: ['.ts', '.js'] 24 | }), 25 | commonjs({ 26 | include: /node_modules/, 27 | transformMixedEsModules: true 28 | }), 29 | common.getCompiler({ 30 | tsconfigOverride: { compilerOptions: { declaration: true } }, 31 | useTsconfigDeclarationDir: true 32 | }) 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /config/rollup.js: -------------------------------------------------------------------------------- 1 | import typescript from 'rollup-plugin-typescript2' 2 | import pkg from '../package.json' 3 | 4 | // 兼容 axios-miniprogram-adapter 和 @bigMeow/axios-miniprogram-adapter 5 | const name = pkg.name.split('/').pop() 6 | const version = pkg.version 7 | 8 | const banner = 9 | `/*! 10 | * axios-miniprogram-adapter ${version} (https://github.com/bigMeow/axios-miniprogram-adapter) 11 | * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md 12 | * Copyright 2018-${(new Date()).getFullYear()} bigMeow. All Rights Reserved 13 | * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE) 14 | */ 15 | ` 16 | 17 | function getCompiler (opt) { 18 | return typescript(opt) 19 | } 20 | 21 | const external = [ 22 | 'axios/lib/helpers/buildURL', 23 | 'axios/lib/core/buildFullPath', 24 | 'axios/lib/utils', 25 | 'axios/lib/core/settle', 26 | 'axios/lib/core/createError' 27 | ] 28 | 29 | export default { 30 | name, 31 | banner, 32 | getCompiler, 33 | external 34 | } 35 | -------------------------------------------------------------------------------- /test/browser/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Mocha 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 18 | 19 | 28 | 29 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 bigmeow 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "axios", 3 | "version": "1.0.0", 4 | "description": "a megalo project", 5 | "main": "index.js", 6 | "private": true, 7 | "scripts": { 8 | "build:wechat": "megalo-cli-service build", 9 | "build:alipay": "megalo-cli-service build --platform alipay", 10 | "build:swan": "megalo-cli-service build --platform swan", 11 | "dev:alipay": "megalo-cli-service serve --platform alipay", 12 | "dev:swan": "megalo-cli-service serve --platform swan", 13 | "dev:wechat": "megalo-cli-service serve", 14 | "lint": "eslint --fix src/**/*.vue" 15 | }, 16 | "author": "bigMeow ", 17 | "license": "ISC", 18 | "babel": { 19 | "presets": [ 20 | "@megalo/app" 21 | ] 22 | }, 23 | "devDependencies": { 24 | "@megalo/babel-preset-app": "^1.0.0-alpha.1", 25 | "@megalo/cli-service": "^1.0.0-alpha.10", 26 | "@megalo/entry": "^0.1.2", 27 | "@megalo/eslint-config-standard": "^1.0.0-alpha.1", 28 | "@megalo/target": "0.5.7", 29 | "@megalo/template-compiler": "^0.9.0", 30 | "eslint": "^5.15.3", 31 | "less": "^3.8.1", 32 | "less-loader": "^4.1.0", 33 | "octoparse": "^0.3.2" 34 | }, 35 | "dependencies": { 36 | "axios": "^0.18.0", 37 | "axios-miniprogram-adapter": "^0.2.3", 38 | "megalo": "^0.9.0" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | require('./specs/wxAdapter.spec') 2 | // var expect = require('expect.js'); 3 | // var axios = require('axios'); 4 | // var wxEnv = require('./wx-env-fake') 5 | // var mpAdapter = require('../dist/index.js'); 6 | 7 | 8 | // describe('单元测试', function() { 9 | 10 | // before(function () { 11 | 12 | // axios.defaults.adapter = mpAdapter 13 | // }) 14 | // this.timeout(3000); 15 | 16 | // describe('功能1', function() { 17 | // it('请求方式', function(done) { 18 | // axios.get('https://api.github.com/users/mzabriskie').then(data => { 19 | // console.log(data) 20 | // done() 21 | // }) 22 | // }) 23 | // it('请求迸发', function(done) { 24 | // axios.all([ 25 | // axios.get('https://api.github.com/users/mzabriskie'), 26 | // axios.get('https://api.github.com/users/mzabriskie/orgs') 27 | // ]).then(axios.spread(function (user, orgs) { 28 | // // console.log('接口1数据:', user.data.avatar_url, user.data.name) 29 | // // console.log('接口2数据:', orgs.data) 30 | // done() 31 | // //expect(orgs.data == true).to.equal(true); 32 | // })) 33 | // // expect(base.name).to.equal('base'); 34 | // }); 35 | // }); 36 | 37 | // // describe('功能2', function() { 38 | // // it('不相等', function() { 39 | // // expect(base.name).not.to.equal(1); 40 | // // }); 41 | // // }); 42 | // }); 43 | -------------------------------------------------------------------------------- /demo/alipay-demo/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alipay-axios-demo", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "axios": { 8 | "version": "0.19.2", 9 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", 10 | "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", 11 | "requires": { 12 | "follow-redirects": "1.5.10" 13 | } 14 | }, 15 | "axios-miniprogram-adapter": { 16 | "version": "0.3.0", 17 | "resolved": "https://registry.npmjs.org/axios-miniprogram-adapter/-/axios-miniprogram-adapter-0.3.0.tgz", 18 | "integrity": "sha512-HFQox9abdxejMMxCv5ki994HAzGi6OOB57RqyZretLo0vN4T/CmVBqdT7PYKKhtn8jPdn8IbPptApQdCvAd6lg==", 19 | "requires": { 20 | "axios": "^0.19.2" 21 | } 22 | }, 23 | "debug": { 24 | "version": "3.1.0", 25 | "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", 26 | "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", 27 | "requires": { 28 | "ms": "2.0.0" 29 | } 30 | }, 31 | "follow-redirects": { 32 | "version": "1.5.10", 33 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", 34 | "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", 35 | "requires": { 36 | "debug": "=3.1.0" 37 | } 38 | }, 39 | "ms": { 40 | "version": "2.0.0", 41 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 42 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /doc/api.md: -------------------------------------------------------------------------------- 1 | ## :bomb: 差异 2 | 由于小程序特性限制,下面的配置在小程序环境下将会自动被忽略 3 | 4 | - timeout 5 | - withCredentials 6 | - xsrfCookieName 7 | - xsrfHeaderName 8 | - onUploadProgress 9 | - onDownloadProgress 10 | 11 | 12 | 13 | ## :warning: 注意 14 | 在mpvue、megalo 等vue转小程序的框架中使用时,由于这些框架修改了webpack的target配置(不修改的话默认值是web),它们的修改代码: 15 | ```js 16 | // mpvue 的 https://github.com/mpvue/mpvue-quickstart/blob/master/template/build/webpack.base.conf.js 17 | target: require('mpvue-webpack-target') 18 | ``` 19 | ```js 20 | //megalo 的 https://github.com/kaola-fed/megalo-demo/blob/master/build/createBaseConfig.js 21 | target: createMegaloTarget( { 22 | compiler: Object.assign( compiler, { } ), 23 | platform, 24 | htmlParse: { 25 | templateName: 'octoParse', 26 | src: _.resolve(`./node_modules/octoparse/lib/platform/${platform}`) 27 | } 28 | } ) 29 | ``` 30 | 所以如果你直接在工程中引入```axios``` 会引起编译报错,这是因为```axios```同时支持了nodejs和浏览器的http请求,你在浏览器使用axios就不打包nodejs相关的代码,在nodejs使用时axios则不打包浏览器相关的xmlHttpRequest对象,从而减少打包的体积,为了实现这个效果,axios的package.json加了下面这行配置: 31 | ```json 32 | // 表示在webpack的target值为 web 时,将代码中的http.js(nodejs环境需要的)引用替换成xhr.js(浏览器环境需要的),从而实现只打包相关平台代码的作用 33 | "browser": { 34 | "./lib/adapters/http.js": "./lib/adapters/xhr.js" 35 | } 36 | ``` 37 | 而webpack配置文件的target被修改后,axios的这个配置就不起作用了,就会去加载nodejs环境的代码,从而导致编译报错 38 | ### :bulb: 解决方案 39 | - 在自己的工程项目里给webpack配置文件增加下面的配置选项([参考例子第59行](https://github.com/bigmeow/axios-miniprogram-adapter/blob/master/demo/miniprograme-example/build/createBaseConfig.js)): 40 | ```js 41 | resolve: { 42 | // https://webpack.docschina.org/configuration/resolve/#resolve-aliasfields 告诉weboack在target被修改后可以尝试去查找下package.json的browser字段 43 | aliasFields: ['browser'] 44 | } 45 | ``` 46 | 这样axios被webpack编译时就不会去加载nodejs而是浏览器端的ajax代码,在小程序中用不上这段代码,大概会增加2kb的包体积大小,不过目前没有办法解决,除非axios官方修改打包策略 47 | 48 | 未修改webpack的target配置 的忽略此项 49 | 50 | 51 | 如果您使用1.x版本的megalo cli 创建的项目,请参照这里进行修改:https://github.com/bigmeow/axios-miniprogram-adapter/blob/master/demo/miniprograme-example-megalo/megalo.config.js 52 | 53 | -------------------------------------------------------------------------------- /demo/miniprograme-native/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "miniprograme-native", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "axios": { 8 | "version": "0.18.1", 9 | "resolved": "http://registry.npmjs.org/axios/-/axios-0.18.1.tgz", 10 | "integrity": "sha512-0BfJq4NSfQXd+SkFdrvFbG7addhYSBA2mQwISr46pD6E5iqkWg02RAs8vyTT/j0RTnoYmeXauBuSv1qKwR179g==", 11 | "requires": { 12 | "follow-redirects": "1.5.10", 13 | "is-buffer": "^2.0.2" 14 | } 15 | }, 16 | "axios-miniprogram-adapter": { 17 | "version": "git+https://github.com/bigmeow/axios-miniprogram-adapter.git#b485752e36cc5bc667e613ac87db41acba260701", 18 | "from": "git+https://github.com/bigmeow/axios-miniprogram-adapter.git", 19 | "requires": { 20 | "axios": "^0.18.0" 21 | } 22 | }, 23 | "debug": { 24 | "version": "3.1.0", 25 | "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", 26 | "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", 27 | "requires": { 28 | "ms": "2.0.0" 29 | } 30 | }, 31 | "follow-redirects": { 32 | "version": "1.5.10", 33 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", 34 | "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", 35 | "requires": { 36 | "debug": "=3.1.0" 37 | } 38 | }, 39 | "is-buffer": { 40 | "version": "2.0.4", 41 | "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz", 42 | "integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A==" 43 | }, 44 | "ms": { 45 | "version": "2.0.0", 46 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 47 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/pages/search-tip.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 60 | 61 | 69 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/is-buffer/index.js: -------------------------------------------------------------------------------- 1 | module.exports = (function() { 2 | var __MODS__ = {}; 3 | var __DEFINE__ = function(modId, func, req) { var m = { exports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; 4 | var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = { exports: {} }; __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); if(typeof m.exports === "object") { Object.keys(m.exports).forEach(function(k) { __MODS__[modId].m.exports[k] = m.exports[k]; }); if(m.exports.__esModule) Object.defineProperty(__MODS__[modId].m.exports, "__esModule", { value: true }); } else { __MODS__[modId].m.exports = m.exports; } } return __MODS__[modId].m.exports; }; 5 | var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; 6 | var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; 7 | __DEFINE__(1544589223617, function(require, module, exports) { 8 | /*! 9 | * Determine if an object is a Buffer 10 | * 11 | * @author Feross Aboukhadijeh 12 | * @license MIT 13 | */ 14 | 15 | // The _isBuffer check is for Safari 5-7 support, because it's missing 16 | // Object.prototype.constructor. Remove this eventually 17 | module.exports = function (obj) { 18 | return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) 19 | } 20 | 21 | function isBuffer (obj) { 22 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 23 | } 24 | 25 | // For Node v0.10 support. Remove this eventually. 26 | function isSlowBuffer (obj) { 27 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) 28 | } 29 | 30 | }, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); }) 31 | return __REQUIRE__(1544589223617); 32 | })() 33 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "axios-miniprogram-adapter", 3 | "version": "0.3.5", 4 | "description": "Axios adapter for miniprogram", 5 | "main": "dist/index.js", 6 | "jsnext:main": "dist/index.esm.js", 7 | "module": "dist/index.esm.js", 8 | "miniprogram": "dist/miniprogram", 9 | "sideEffects": false, 10 | "scripts": { 11 | "rename": "node rename.js", 12 | "clean": "rimraf ./dist", 13 | "lint": "eslint -c config/.eslintrc.js src --ext .ts --fix", 14 | "build:self": "rollup -c config/rollup.config.js", 15 | "build:esm": "rollup -c config/rollup.config.esm.js", 16 | "build:aio": "rollup -c config/rollup.config.aio.js", 17 | "build:self.all": "cross-env NODE_ENV=production npm run build:self", 18 | "build": "npm run clean && npm run build:self && npm run build:esm && npm run build:aio && npm run build:self.all", 19 | "test": "npm run lint && npm run build && mocha", 20 | "mocha": "mocha", 21 | "release": "git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags" 22 | }, 23 | "author": "bigMeow(lizong9527@gmail.com)", 24 | "license": "MIT", 25 | "repository": { 26 | "type": "git", 27 | "url": "git://github.com/bigMeow/axios-miniprogram-adapter.git" 28 | }, 29 | "bugs": { 30 | "url": "https://github.com/bigMeow/axios-miniprogram-adapter/issues" 31 | }, 32 | "keywords": [ 33 | "axios", 34 | "adapter", 35 | "wechat", 36 | "miniprogram", 37 | "微信小程序" 38 | ], 39 | "devDependencies": { 40 | "@rollup/plugin-commonjs": "^13.0.0", 41 | "@rollup/plugin-node-resolve": "^8.1.0", 42 | "@vue/eslint-config-standard": "^4.0.0", 43 | "@vue/eslint-config-typescript": "^3.1.1", 44 | "cdkit": "^1.1.0", 45 | "cross-env": "^5.2.0", 46 | "eslint": "^5.9.0", 47 | "eslint-plugin-vue": "^5.0.0-beta.5", 48 | "expect.js": "^0.3.1", 49 | "miniprogram-api-typings": "^2.10.1-1", 50 | "mocha": "^5.2.0", 51 | "rimraf": "2.6.2", 52 | "rollup": "^2.20.0", 53 | "rollup-plugin-sourcemaps": "^0.6.2", 54 | "rollup-plugin-typescript2": "^0.27.1", 55 | "tslib": "^1.9.3", 56 | "typescript": "^3.1.6" 57 | }, 58 | "dependencies": { 59 | "axios": "^0.19.2" 60 | } 61 | } -------------------------------------------------------------------------------- /demo/alipay-demo/pages/index/index.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import mpAdapter from 'axios-miniprogram-adapter' 3 | axios.defaults.adapter = mpAdapter 4 | 5 | // 创建实例 设置baseURL 6 | const instance = axios.create({ 7 | baseURL: 'https://wx.jk724.com' 8 | }) 9 | 10 | Page({ 11 | async handleRequestByGet() { 12 | my.showLoading(); 13 | try { 14 | const resp = await instance.get('/api/HotSearchWords') 15 | console.log('GET请求成功:', resp) 16 | 17 | } catch (error) { 18 | // 19 | } finally { 20 | my.hideLoading(); 21 | } 22 | }, 23 | async handleRequestByPOST() { 24 | my.showLoading(); 25 | try { 26 | const resp = await instance.post('https://t.captcha.qq.com/cap_union_new_verify') 27 | console.log('POST请求成功:', resp) 28 | 29 | } catch (error) { 30 | // 31 | } finally { 32 | my.hideLoading(); 33 | } 34 | }, 35 | // get请求带参数 36 | async handleRequestByGetParams() { 37 | my.showLoading(); 38 | try { 39 | const resp = await instance({ 40 | url: '/api/HotSearchWords', 41 | params: { 42 | name: '我是参数' 43 | } 44 | }) 45 | console.log('get带参数请求成功:', resp) 46 | 47 | } catch (error) { 48 | // 49 | } finally { 50 | my.hideLoading(); 51 | } 52 | }, 53 | // post请求带参数(注意查看请求头的 content-type: application/json 和 请求体的 Reuquest Payload) 54 | async handleRequestByPOSTParams() { 55 | my.showLoading(); 56 | try { 57 | const resp = await instance({ 58 | method: 'POST', 59 | url: 'https://t.captcha.qq.com/cap_union_new_verify', 60 | data: { 61 | name: '我是参数' 62 | } 63 | }) 64 | console.log('post带参数请求成功:', resp) 65 | 66 | } catch (error) { 67 | // 68 | } finally { 69 | my.hideLoading(); 70 | } 71 | }, 72 | // 自定义请求头参数 73 | async handleRequestByHeaders() { 74 | my.showLoading(); 75 | try { 76 | const resp = await instance({ 77 | method: 'GET', 78 | url: '/api/HotSearchWords', 79 | headers: { 80 | Authorization: 'im a token' 81 | } 82 | }) 83 | console.log('post带参数请求成功:', resp) 84 | 85 | } catch (error) { 86 | // 87 | } finally { 88 | my.hideLoading(); 89 | } 90 | }, 91 | // 修改content type (注意查看请求头的 content-type: application/x-www-form-urlencoded 和 请求体的 form data) 92 | async handleRequestByContentType() { 93 | my.showLoading(); 94 | try { 95 | const resp = await instance({ 96 | method: 'POST', 97 | url: 'https://t.captcha.qq.com/cap_union_new_verify', 98 | headers: { 99 | 'content-type': 'application/x-www-form-urlencoded' 100 | }, 101 | data: { 102 | name: '我是参数' 103 | } 104 | }) 105 | console.log('post带参数请求成功:', resp) 106 | 107 | } catch (error) { 108 | // 109 | } finally { 110 | my.hideLoading(); 111 | } 112 | } 113 | }); 114 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/ms/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["index.js"],"names":[],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"index.js","sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n"]} -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { AxiosRequestConfig, AxiosPromise } from 'axios' 2 | import utils from 'axios/lib/utils' 3 | import settle from 'axios/lib/core/settle' 4 | import buildURL from 'axios/lib/helpers/buildURL' 5 | import buildFullPath from 'axios/lib/core/buildFullPath' 6 | import encode from './utils/encoder' 7 | import { getRequest, transformError, transformResponse, transformConfig } from './utils/platForm' 8 | 9 | const isJSONstr = str => { 10 | try { 11 | return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]' 12 | } catch (error) { 13 | return false 14 | } 15 | } 16 | export default function mpAdapter (config: AxiosRequestConfig, { 17 | transformRequestOption = requestOption => requestOption 18 | }: { 19 | transformRequestOption?: (requestOption: any) => any 20 | } = {}): AxiosPromise { 21 | const request = getRequest() 22 | return new Promise((resolve, reject) => { 23 | let requestTask: void | WechatMiniprogram.RequestTask 24 | let requestData = config.data 25 | let requestHeaders = config.headers 26 | // baidu miniprogram only support upperCase 27 | let requestMethod = (config.method && config.method.toUpperCase()) || 'GET' 28 | // miniprogram network request config 29 | const mpRequestOption: WechatMiniprogram.RequestOption = { 30 | method: requestMethod as | 'OPTIONS' 31 | | 'GET' 32 | | 'HEAD' 33 | | 'POST' 34 | | 'PUT' 35 | | 'DELETE' 36 | | 'TRACE' 37 | | 'CONNECT', 38 | url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer), 39 | timeout: config.timeout, 40 | // Listen for success 41 | success: (mpResponse: any) => { 42 | const response = transformResponse(mpResponse, config, mpRequestOption) 43 | settle(resolve, reject, response) 44 | }, 45 | // Handle request Exception 46 | fail: (error) => { 47 | transformError(error, reject, config) 48 | }, 49 | complete () { 50 | requestTask = undefined 51 | } 52 | } 53 | 54 | // HTTP basic authentication 55 | if (config.auth) { 56 | const [username, password] = [config.auth.username || '', config.auth.password || ''] 57 | requestHeaders.Authorization = 'Basic ' + encode(username + ':' + password) 58 | } 59 | 60 | // Add headers to the request 61 | utils.forEach(requestHeaders, function setRequestHeader (val: any, key: string) { 62 | const _header = key.toLowerCase() 63 | if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') { 64 | // Remove Content-Type if data is undefined 65 | // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer' 66 | delete requestHeaders[key] 67 | } 68 | }) 69 | mpRequestOption.header = requestHeaders 70 | 71 | // Add responseType to request if needed 72 | if (config.responseType) { 73 | mpRequestOption.responseType = config.responseType as 'text' | 'arraybuffer' 74 | } 75 | 76 | if (config.cancelToken) { 77 | // Handle cancellation 78 | config.cancelToken.promise.then(function onCanceled (cancel) { 79 | if (!requestTask) { 80 | return 81 | } 82 | requestTask.abort() 83 | reject(cancel) 84 | // Clean up request 85 | requestTask = undefined 86 | }) 87 | } 88 | // Converting JSON strings to objects is handed over to the MiniPrograme 89 | if (isJSONstr(requestData)) { 90 | requestData = JSON.parse(requestData) 91 | } 92 | if (requestData !== undefined) { 93 | mpRequestOption.data = requestData 94 | } 95 | requestTask = request(transformRequestOption(transformConfig(mpRequestOption))) 96 | }) 97 | } 98 | -------------------------------------------------------------------------------- /src/utils/platForm.ts: -------------------------------------------------------------------------------- 1 | import createError from 'axios/lib/core/createError' 2 | import { AxiosResponse, AxiosRequestConfig } from 'axios' 3 | 4 | const enum EnumPlatForm { 5 | 微信 = 'wechat', 6 | 支付宝 = 'alipay', 7 | 百度 = 'baidu', 8 | 钉钉 = 'dd' 9 | } 10 | 11 | let platFormName: EnumPlatForm = EnumPlatForm.微信 12 | 13 | /** 14 | * 获取各个平台的请求函数 15 | */ 16 | export function getRequest (): (option: WechatMiniprogram.RequestOption) => WechatMiniprogram.RequestTask { 17 | switch (true) { 18 | case typeof wx === 'object': 19 | platFormName = EnumPlatForm.微信 20 | return wx.request.bind(wx) 21 | case typeof swan === 'object': 22 | platFormName = EnumPlatForm.百度 23 | return swan.request.bind(swan) 24 | case typeof dd === 'object': 25 | platFormName = EnumPlatForm.钉钉 26 | // https://open.dingtalk.com/document/orgapp-client/send-network-requests 27 | return dd.httpRequest.bind(dd) 28 | case typeof my === 'object': 29 | /** 30 | * remark: 31 | * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。 32 | * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。 33 | * my.request的请求头默认值为{'content-type': 'application/json'}。 34 | * 还有个 dd.httpRequest 35 | */ 36 | platFormName = EnumPlatForm.支付宝 37 | return (my.request || my.httpRequest).bind(my) 38 | default: 39 | return wx.request.bind(wx) 40 | } 41 | } 42 | 43 | /** 44 | * 处理各平台返回的响应数据,抹平差异 45 | * @param mpResponse 46 | * @param config axios处理过的请求配置对象 47 | * @param request 小程序的调用发起请求时,传递给小程序api的实际配置 48 | */ 49 | export function transformResponse (mpResponse: MpResponse, config: AxiosRequestConfig, mpRequestOption: WechatMiniprogram.RequestOption): AxiosResponse { 50 | const headers = mpResponse.header || mpResponse.headers 51 | const status = mpResponse.statusCode || mpResponse.status 52 | 53 | let statusText = '' 54 | if (status === 200) { 55 | statusText = 'OK' 56 | } else if (status === 400) { 57 | statusText = 'Bad Request' 58 | } 59 | 60 | const response: AxiosResponse = { 61 | data: mpResponse.data, 62 | status, 63 | statusText, 64 | headers, 65 | config, 66 | request: mpRequestOption 67 | } 68 | return response 69 | } 70 | 71 | /** 72 | * 处理各平台返回的错误信息,抹平差异 73 | * @param error 小程序api返回的错误对象 74 | * @param reject 上层的promise reject 函数 75 | * @param config 76 | */ 77 | export function transformError (error:any, reject, config) { 78 | switch (platFormName) { 79 | case EnumPlatForm.微信: 80 | if (error.errMsg.indexOf('request:fail abort') !== -1) { 81 | // Handle request cancellation (as opposed to a manual cancellation) 82 | reject(createError('Request aborted', config, 'ECONNABORTED', '')) 83 | } else if (error.errMsg.indexOf('timeout') !== -1) { 84 | // timeout 85 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '')) 86 | } else { 87 | // NetWordError 88 | reject(createError('Network Error', config, null, '')) 89 | } 90 | break 91 | case EnumPlatForm.钉钉: 92 | case EnumPlatForm.支付宝: 93 | // https://docs.alipay.com/mini/api/network 94 | if ([14, 19].includes(error.error)) { 95 | reject(createError('Request aborted', config, 'ECONNABORTED', '', error)) 96 | } else if ([13].includes(error.error)) { 97 | // timeout 98 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error)) 99 | } else { 100 | // NetWordError 101 | reject(createError('Network Error', config, null, '', error)) 102 | } 103 | break 104 | case EnumPlatForm.百度: 105 | // TODO error.errCode 106 | reject(createError('Network Error', config, null, '')) 107 | break 108 | } 109 | } 110 | 111 | /** 112 | * 将axios的请求配置,转换成各个平台都支持的请求config 113 | * @param config 114 | */ 115 | export function transformConfig (config: MpRequestConfig): any { 116 | if ([EnumPlatForm.支付宝, EnumPlatForm.钉钉].includes(platFormName)) { 117 | config.headers = config.header 118 | delete config.header 119 | if (EnumPlatForm.钉钉 === platFormName && config.method !== 'GET' && config.headers?.['Content-Type'] === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') { 120 | // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化 121 | config.data = JSON.stringify(config.data) 122 | } 123 | } 124 | return config 125 | } 126 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/ms/index.js: -------------------------------------------------------------------------------- 1 | module.exports = (function() { 2 | var __MODS__ = {}; 3 | var __DEFINE__ = function(modId, func, req) { var m = { exports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; 4 | var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = { exports: {} }; __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); if(typeof m.exports === "object") { Object.keys(m.exports).forEach(function(k) { __MODS__[modId].m.exports[k] = m.exports[k]; }); if(m.exports.__esModule) Object.defineProperty(__MODS__[modId].m.exports, "__esModule", { value: true }); } else { __MODS__[modId].m.exports = m.exports; } } return __MODS__[modId].m.exports; }; 5 | var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; 6 | var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; 7 | __DEFINE__(1544589223618, function(require, module, exports) { 8 | /** 9 | * Helpers. 10 | */ 11 | 12 | var s = 1000; 13 | var m = s * 60; 14 | var h = m * 60; 15 | var d = h * 24; 16 | var y = d * 365.25; 17 | 18 | /** 19 | * Parse or format the given `val`. 20 | * 21 | * Options: 22 | * 23 | * - `long` verbose formatting [false] 24 | * 25 | * @param {String|Number} val 26 | * @param {Object} [options] 27 | * @throws {Error} throw an error if val is not a non-empty string or a number 28 | * @return {String|Number} 29 | * @api public 30 | */ 31 | 32 | module.exports = function(val, options) { 33 | options = options || {}; 34 | var type = typeof val; 35 | if (type === 'string' && val.length > 0) { 36 | return parse(val); 37 | } else if (type === 'number' && isNaN(val) === false) { 38 | return options.long ? fmtLong(val) : fmtShort(val); 39 | } 40 | throw new Error( 41 | 'val is not a non-empty string or a valid number. val=' + 42 | JSON.stringify(val) 43 | ); 44 | }; 45 | 46 | /** 47 | * Parse the given `str` and return milliseconds. 48 | * 49 | * @param {String} str 50 | * @return {Number} 51 | * @api private 52 | */ 53 | 54 | function parse(str) { 55 | str = String(str); 56 | if (str.length > 100) { 57 | return; 58 | } 59 | var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( 60 | str 61 | ); 62 | if (!match) { 63 | return; 64 | } 65 | var n = parseFloat(match[1]); 66 | var type = (match[2] || 'ms').toLowerCase(); 67 | switch (type) { 68 | case 'years': 69 | case 'year': 70 | case 'yrs': 71 | case 'yr': 72 | case 'y': 73 | return n * y; 74 | case 'days': 75 | case 'day': 76 | case 'd': 77 | return n * d; 78 | case 'hours': 79 | case 'hour': 80 | case 'hrs': 81 | case 'hr': 82 | case 'h': 83 | return n * h; 84 | case 'minutes': 85 | case 'minute': 86 | case 'mins': 87 | case 'min': 88 | case 'm': 89 | return n * m; 90 | case 'seconds': 91 | case 'second': 92 | case 'secs': 93 | case 'sec': 94 | case 's': 95 | return n * s; 96 | case 'milliseconds': 97 | case 'millisecond': 98 | case 'msecs': 99 | case 'msec': 100 | case 'ms': 101 | return n; 102 | default: 103 | return undefined; 104 | } 105 | } 106 | 107 | /** 108 | * Short format for `ms`. 109 | * 110 | * @param {Number} ms 111 | * @return {String} 112 | * @api private 113 | */ 114 | 115 | function fmtShort(ms) { 116 | if (ms >= d) { 117 | return Math.round(ms / d) + 'd'; 118 | } 119 | if (ms >= h) { 120 | return Math.round(ms / h) + 'h'; 121 | } 122 | if (ms >= m) { 123 | return Math.round(ms / m) + 'm'; 124 | } 125 | if (ms >= s) { 126 | return Math.round(ms / s) + 's'; 127 | } 128 | return ms + 'ms'; 129 | } 130 | 131 | /** 132 | * Long format for `ms`. 133 | * 134 | * @param {Number} ms 135 | * @return {String} 136 | * @api private 137 | */ 138 | 139 | function fmtLong(ms) { 140 | return plural(ms, d, 'day') || 141 | plural(ms, h, 'hour') || 142 | plural(ms, m, 'minute') || 143 | plural(ms, s, 'second') || 144 | ms + ' ms'; 145 | } 146 | 147 | /** 148 | * Pluralization helper. 149 | */ 150 | 151 | function plural(ms, n, name) { 152 | if (ms < n) { 153 | return; 154 | } 155 | if (ms < n * 1.5) { 156 | return Math.floor(ms / n) + ' ' + name; 157 | } 158 | return Math.ceil(ms / n) + ' ' + name + 's'; 159 | } 160 | 161 | }, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); }) 162 | return __REQUIRE__(1544589223618); 163 | })() 164 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /demo/miniprograme-native/index/index.js: -------------------------------------------------------------------------------- 1 | const app = getApp() 2 | import axios from 'axios' 3 | import mpAdapter from 'axios-miniprogram-adapter' 4 | axios.defaults.adapter = mpAdapter 5 | Page({ 6 | data: { 7 | 8 | }, 9 | // 基本请求调用 10 | handleBase () { 11 | // 创建实例 设置baseURL 12 | const instance = axios.create({ 13 | baseURL: 'https://easy-mock.com' 14 | }) 15 | // 设置token 16 | instance.defaults.headers.common['Authorization'] = 'I am a token'; 17 | instance.get('/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByGet') 18 | .then(resp => { 19 | console.log('GET请求成功:', resp) 20 | }) 21 | 22 | instance.post('/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByPost') 23 | .then(resp => { 24 | console.log('Post请求成功:', resp) 25 | }) 26 | 27 | instance.request({ 28 | url: 'https://easy-mock.com/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByGet', 29 | params: { 30 | name: '帅锅get Params', 31 | age: '18' 32 | } 33 | }) 34 | .then(resp => { 35 | console.log('axios.request GET请求带参数成功:', resp) 36 | }) 37 | 38 | instance.request({ 39 | url: 'https://easy-mock.com/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByPost', 40 | method: 'POST', 41 | data: { 42 | name: '帅锅post Data', 43 | age: '18' 44 | } 45 | }) 46 | .then(resp => { 47 | console.log('axios.request POST请求带参数成功:', resp) 48 | }) 49 | 50 | 51 | }, 52 | // 多个接口迸发调用后统一处理数据 53 | all () { 54 | axios.all([ 55 | axios.get('https://api.github.com/users/mzabriskie'), 56 | axios.get('https://api.github.com/users/mzabriskie/orgs') 57 | ]).then(axios.spread(function (user, orgs) { 58 | console.log('接口1数据:', user.data.avatar_url, user.data.name) 59 | console.log('接口2数据:', orgs.data) 60 | })); 61 | }, 62 | // 错误捕获 63 | catchError () { 64 | axios.post('https://easy-mock.com/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByPost22') 65 | .then(resp => { 66 | console.log('Post请求成功:', resp) 67 | }).catch(({message, name, config, code, stack, request , response}) => { 68 | console.log(`捕获到了异常:${message}\n ${name} \n ${config} \n ${code}\n`,request , response) 69 | }) 70 | }, 71 | // 数据拦截替换 72 | transformResponseData () { 73 | var ISO_8601 = /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})Z/; 74 | function formatDate(d) { 75 | return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear(); 76 | } 77 | 78 | axios.get('https://api.github.com/users/mzabriskie', { 79 | transformResponse: axios.defaults.transformResponse.concat(function (data, headers) { 80 | Object.keys(data).forEach(function (k) { 81 | if (ISO_8601.test(data[k])) { 82 | console.log(`字段${k}转换前:`, data[k]) 83 | data[k] = new Date(Date.parse(data[k])); 84 | console.log(`字段${k}转换后:`, data[k]) 85 | } 86 | }); 87 | return data; 88 | }) 89 | }) 90 | .then(function (res) { 91 | console.log('useravatar', res.data.avatar_url) 92 | console.log('username', res.data.name) 93 | console.log('created', formatDate(res.data.created_at)) 94 | console.log('updated', formatDate(res.data.updated_at)) 95 | }) 96 | }, 97 | // 拦截器测试 98 | interceptors () { 99 | const instance = axios.create({ 100 | baseURL: 'https://easy-mock.com' 101 | }) 102 | // 请求拦截器 103 | instance.interceptors.request.use(function (config) { 104 | // 发送请求之前你可以在这里对config做一些羞羞的事情 105 | console.log('请求被拦截到了,加点料', config) 106 | config.headers['Authorization'] = '123ba' 107 | return config; 108 | }, function (error) { 109 | // Do something with request error 110 | return Promise.reject(error); 111 | }); 112 | 113 | // 添加一个响应拦截器 114 | instance.interceptors.response.use(function (response) { 115 | console.log('拦截到响应数据了,我过滤下,过滤前的数据:', response) 116 | // Do something with response data 117 | return response.data; 118 | }, function (error) { 119 | // Do something with response error 120 | return Promise.reject(error); 121 | }); 122 | 123 | instance.get('/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByGet') 124 | .then(resp => { 125 | console.log('经过拦截器后收到的数据:', resp) 126 | }) 127 | }, 128 | // 请求取消 129 | requestCancel () { 130 | var CancelToken = axios.CancelToken; 131 | var cancel 132 | 133 | axios.get('https://easy-mock.com/mock/5be12b95f7aed41684f2daea/axiosTest/getPersonByGet', { 134 | cancelToken: new CancelToken(function executor(c) { 135 | // An executor function receives a cancel function as a parameter 136 | cancel = c 137 | }) 138 | }).catch(error => { 139 | if (axios.isCancel(error)) { 140 | console.log('自己取消了请求', error) 141 | } 142 | }) 143 | 144 | // cancel the request 145 | cancel('取消请求') 146 | }, 147 | 148 | handleJump () { 149 | wx.navigateTo({ 150 | url: '../search-tip/index' 151 | }) 152 | } 153 | }) 154 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/axios-miniprogram-adapter/index.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e["axios-miniprogram-adapter"]=t()}(this,function(){"use strict";function r(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var t=Object.prototype.toString;function i(e){return"[object Array]"===t.call(e)}function n(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===t.call(e)}function a(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),i(e))for(var r=0,n=e.length;r>8-o%1*8)){if(255<(r=n.charCodeAt(o+=.75)))throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");t=t<<8|r}return a}(r+":"+i)}0!==m.timeout&&l('The "timeout" option is not supported by miniprogram. For more information about usage see "https://developers.weixin.qq.com/miniprogram/dev/framework/config.html#全局配置"'),u.forEach(o,function(e,t){var r=t.toLowerCase();if(void 0===n&&"content-type"===r||"referer"===r)delete o[t];else if("string"==typeof n&&"content-type"===r&&"application/x-www-form-urlencoded"===e)try{n=JSON.parse(n)}catch(e){}}),y.header=o,m.responseType&&(y.responseType=m.responseType),m.cancelToken&&m.cancelToken.promise.then(function(e){t&&(t.abort(),p(e),t=void 0)}),void 0!==n&&(y.data=n),t=a(y)})}}); 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![license](https://img.shields.io/npm/l/axios-miniprogram-adapter.svg)](https://github.com/bigmeow/axios-miniprogram-adapter/blob/master/LICENSE) 2 | [![Build Status](https://travis-ci.org/bigmeow/axios-miniprogram-adapter.svg?branch=master)](https://travis-ci.org/bigMeow/axios-miniprogram-adapter) 3 | Version 4 | [![NPM downloads](http://img.shields.io/npm/dm/axios-miniprogram-adapter.svg?style=flat-square)](http://www.npmtrends.com/axios-miniprogram-adapter) 5 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/bigMeow/axios-miniprogram-adapter.svg)](http://isitmaintained.com/project/bigMeow/axios-miniprogram-adapter "Percentage of issues still open") 6 | 7 | axios的小程序适配器,支持在各个平台小程序中使用axios. 8 | 9 | Taro 适配器请点击[这里](https://github.com/bigmeow/taro-platform/tree/master/packages/axios-taro-adapter) 10 | 11 | ## :star: 特性 12 | 13 | - 支持微信、支付宝、钉钉、百度小程序,放心使用axios,最大限度复用web端axios的代码 14 | - 支持TypeScript 15 | 16 | 17 | 18 | 19 | 25 | 31 | 37 | 43 | 44 | 45 |
20 | 21 | 微信小程序 22 |
微信小程序
23 |
24 |
26 | 27 | 支付宝小程序 28 |
支付宝小程序
29 |
30 |
32 | 33 | 钉钉小程序 34 |
钉钉小程序
35 |
36 |
38 | 39 | 百度小程序 40 |
百度小程序
41 |
42 |
46 | 47 | ## 催更、钉钉交流群: 48 | 49 | 50 | 51 | ## :open_file_folder: 目录介绍 52 | 53 | ``` 54 | . 55 | ├── demo 使用demo 56 | ├── dist 编译产出代码 57 | ├── doc 项目文档 58 | ├── src 源代码目录 59 | ├── test 单元测试 60 | ├── CHANGELOG.md 变更日志 61 | └── TODO.md 计划功能 62 | ``` 63 | 64 | ## :rocket: 使用者指南 65 | ### 1.如果你是webpack等环境 66 | 67 | 通过npm下载安装代码 68 | 69 | ```bash 70 | $ npm i axios axios-miniprogram-adapter 71 | ``` 72 | 73 | ```js 74 | import axios from 'axios' 75 | import mpAdapter from 'axios-miniprogram-adapter' 76 | axios.defaults.adapter = mpAdapter 77 | // or with extra config transformer 78 | axios.defaults.adapter = config => mpAdapter(config, { transformRequestOption: requestOption => { /* modify requestOption here */ return requestOption } }) 79 | ``` 80 | 81 | ### 2.如果你没有使用任何脚手架工具 82 | 直接使用小程序开发工具自带的[```构建npm```](https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html),请按下面几个步骤引入: 83 | - 确保项目目录下有package.json文件,已有的跳过这一步 84 | ``` bash 85 | $ npm init 86 | ``` 87 | - 安装 88 | ``` base 89 | $ npm i axios axios-miniprogram-adapter 90 | ``` 91 | - 在小程序开发者工具中依次找到并点击`工具`->`构建npm`,构建完成后你的项目目录会多出一个`miniprogram_npm`目录 92 | 93 | - 代码引入使用 94 | ```js 95 | import axios from 'axios' 96 | import mpAdapter from 'axios-miniprogram-adapter' 97 | axios.defaults.adapter = mpAdapter 98 | ``` 99 | 100 | 这里有一个代码片段demo可直接供你使用:[https://developers.weixin.qq.com/s/oIqQtBml7F4N](https://developers.weixin.qq.com/s/oIqQtBml7F4N),DEMO源码[点这里](https://github.com/bigmeow/axios-miniprogram-adapter/tree/master/demo/miniprograme-native)也可查看 101 | 102 | ### 3.如果你没有使用任何脚手架工具且npm也不用(不推荐) 103 | 直接拷贝编译后的[axios](https://github.com/axios/axios/tree/master/dist)、[axios-miniprogram-adapter](https://github.com/bigmeow/axios-miniprogram-adapter/tree/master/dist/miniprogram)到项目中: 104 | ```js 105 | import axios from '你的目录/axios.js' 106 | import mpAdapter from '你的目录/axios-miniprogram-adapter.js' 107 | axios.defaults.adapter = mpAdapter 108 | ``` 109 | 110 | ### 三种方式区别 111 | 小程序自带的npm不支持解析node_modules中的库再有外部依赖:例如本库中依赖了```axios```库的某些工具包,在源码中有下面的代码: 112 | ```js 113 | import utils from 'axios/lib/utils' 114 | ``` 115 | 在小程序开发工具中会报错,找不到此依赖。为此,我将依赖打包到一起,这样带来的问题是库的体积多了2kb,基于此,强烈推荐你使用类似于webpack的脚手架工具开发 116 | 117 | ## :bookmark_tabs: 文档 118 | - 同axios官方仓库一致 119 | - [与官方API的差异、注意事项](https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md) 120 | 121 | ## :chestnut: Demo 122 | 打开小程序开发者工具,根据不同平台,选择各自的目录作为项目根目录: 123 | - 微信```axios-miniprogram-adapter/demo/miniprograme-example/dist-wechat``` 124 | - 支付宝、钉钉```axios-miniprogram-adapter/demo/miniprograme-example/dist-alipay``` 125 | - 百度 ```axios-miniprogram-adapter/demo/miniprograme-example/dist-swan``` 126 | 127 | 该demo示范了几个常用功能的用法: 128 | 129 | 130 | 131 | [点击查看代码具体用法示例](https://github.com/bigmeow/axios-miniprogram-adapter/blob/master/demo/miniprograme-example/src/pages/index/index.vue) 132 | 133 | ## :gear: 更新日志 134 | [CHANGELOG.md](https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/CHANGELOG.md) 135 | 136 | ## :airplane: 计划列表 137 | [TODO.md](https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/TODO.md) 138 | 139 | -------------------------------------------------------------------------------- /demo/miniprograme-example-megalo/src/pages/index.vue: -------------------------------------------------------------------------------- 1 | 13 | 14 | 172 | 173 | 178 | -------------------------------------------------------------------------------- /dist/index.esm.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * axios-miniprogram-adapter 0.3.5 (https://github.com/bigMeow/axios-miniprogram-adapter) 3 | * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md 4 | * Copyright 2018-2022 bigMeow. All Rights Reserved 5 | * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE) 6 | */ 7 | 8 | import utils from 'axios/lib/utils'; 9 | import settle from 'axios/lib/core/settle'; 10 | import buildURL from 'axios/lib/helpers/buildURL'; 11 | import buildFullPath from 'axios/lib/core/buildFullPath'; 12 | import createError from 'axios/lib/core/createError'; 13 | 14 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 15 | // encoder 16 | function encoder(input) { 17 | var str = String(input); 18 | // initialize result and counter 19 | var block; 20 | var charCode; 21 | var idx = 0; 22 | var map = chars; 23 | var output = ''; 24 | for (; 25 | // if the next str index does not exist: 26 | // change the mapping table to "=" 27 | // check if d has no fractional digits 28 | str.charAt(idx | 0) || (map = '=', idx % 1); 29 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 30 | output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { 31 | charCode = str.charCodeAt(idx += 3 / 4); 32 | if (charCode > 0xFF) { 33 | throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); 34 | } 35 | block = block << 8 | charCode; 36 | } 37 | return output; 38 | } 39 | 40 | var platFormName = "wechat" /* 微信 */; 41 | /** 42 | * 获取各个平台的请求函数 43 | */ 44 | function getRequest() { 45 | switch (true) { 46 | case typeof wx === 'object': 47 | platFormName = "wechat" /* 微信 */; 48 | return wx.request.bind(wx); 49 | case typeof swan === 'object': 50 | platFormName = "baidu" /* 百度 */; 51 | return swan.request.bind(swan); 52 | case typeof dd === 'object': 53 | platFormName = "dd" /* 钉钉 */; 54 | // https://open.dingtalk.com/document/orgapp-client/send-network-requests 55 | return dd.httpRequest.bind(dd); 56 | case typeof my === 'object': 57 | /** 58 | * remark: 59 | * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。 60 | * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。 61 | * my.request的请求头默认值为{'content-type': 'application/json'}。 62 | * 还有个 dd.httpRequest 63 | */ 64 | platFormName = "alipay" /* 支付宝 */; 65 | return (my.request || my.httpRequest).bind(my); 66 | default: 67 | return wx.request.bind(wx); 68 | } 69 | } 70 | /** 71 | * 处理各平台返回的响应数据,抹平差异 72 | * @param mpResponse 73 | * @param config axios处理过的请求配置对象 74 | * @param request 小程序的调用发起请求时,传递给小程序api的实际配置 75 | */ 76 | function transformResponse(mpResponse, config, mpRequestOption) { 77 | var headers = mpResponse.header || mpResponse.headers; 78 | var status = mpResponse.statusCode || mpResponse.status; 79 | var statusText = ''; 80 | if (status === 200) { 81 | statusText = 'OK'; 82 | } 83 | else if (status === 400) { 84 | statusText = 'Bad Request'; 85 | } 86 | var response = { 87 | data: mpResponse.data, 88 | status: status, 89 | statusText: statusText, 90 | headers: headers, 91 | config: config, 92 | request: mpRequestOption 93 | }; 94 | return response; 95 | } 96 | /** 97 | * 处理各平台返回的错误信息,抹平差异 98 | * @param error 小程序api返回的错误对象 99 | * @param reject 上层的promise reject 函数 100 | * @param config 101 | */ 102 | function transformError(error, reject, config) { 103 | switch (platFormName) { 104 | case "wechat" /* 微信 */: 105 | if (error.errMsg.indexOf('request:fail abort') !== -1) { 106 | // Handle request cancellation (as opposed to a manual cancellation) 107 | reject(createError('Request aborted', config, 'ECONNABORTED', '')); 108 | } 109 | else if (error.errMsg.indexOf('timeout') !== -1) { 110 | // timeout 111 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '')); 112 | } 113 | else { 114 | // NetWordError 115 | reject(createError('Network Error', config, null, '')); 116 | } 117 | break; 118 | case "dd" /* 钉钉 */: 119 | case "alipay" /* 支付宝 */: 120 | // https://docs.alipay.com/mini/api/network 121 | if ([14, 19].includes(error.error)) { 122 | reject(createError('Request aborted', config, 'ECONNABORTED', '', error)); 123 | } 124 | else if ([13].includes(error.error)) { 125 | // timeout 126 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error)); 127 | } 128 | else { 129 | // NetWordError 130 | reject(createError('Network Error', config, null, '', error)); 131 | } 132 | break; 133 | case "baidu" /* 百度 */: 134 | // TODO error.errCode 135 | reject(createError('Network Error', config, null, '')); 136 | break; 137 | } 138 | } 139 | /** 140 | * 将axios的请求配置,转换成各个平台都支持的请求config 141 | * @param config 142 | */ 143 | function transformConfig(config) { 144 | var _a; 145 | if (["alipay" /* 支付宝 */, "dd" /* 钉钉 */].includes(platFormName)) { 146 | config.headers = config.header; 147 | delete config.header; 148 | if ("dd" /* 钉钉 */ === platFormName && config.method !== 'GET' && ((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') { 149 | // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化 150 | config.data = JSON.stringify(config.data); 151 | } 152 | } 153 | return config; 154 | } 155 | 156 | var isJSONstr = function (str) { 157 | try { 158 | return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]'; 159 | } 160 | catch (error) { 161 | return false; 162 | } 163 | }; 164 | function mpAdapter(config, _a) { 165 | var _b = (_a === void 0 ? {} : _a).transformRequestOption, transformRequestOption = _b === void 0 ? function (requestOption) { return requestOption; } : _b; 166 | var request = getRequest(); 167 | return new Promise(function (resolve, reject) { 168 | var requestTask; 169 | var requestData = config.data; 170 | var requestHeaders = config.headers; 171 | // baidu miniprogram only support upperCase 172 | var requestMethod = (config.method && config.method.toUpperCase()) || 'GET'; 173 | // miniprogram network request config 174 | var mpRequestOption = { 175 | method: requestMethod, 176 | url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer), 177 | timeout: config.timeout, 178 | // Listen for success 179 | success: function (mpResponse) { 180 | var response = transformResponse(mpResponse, config, mpRequestOption); 181 | settle(resolve, reject, response); 182 | }, 183 | // Handle request Exception 184 | fail: function (error) { 185 | transformError(error, reject, config); 186 | }, 187 | complete: function () { 188 | requestTask = undefined; 189 | } 190 | }; 191 | // HTTP basic authentication 192 | if (config.auth) { 193 | var _a = [config.auth.username || '', config.auth.password || ''], username = _a[0], password = _a[1]; 194 | requestHeaders.Authorization = 'Basic ' + encoder(username + ':' + password); 195 | } 196 | // Add headers to the request 197 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 198 | var _header = key.toLowerCase(); 199 | if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') { 200 | // Remove Content-Type if data is undefined 201 | // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer' 202 | delete requestHeaders[key]; 203 | } 204 | }); 205 | mpRequestOption.header = requestHeaders; 206 | // Add responseType to request if needed 207 | if (config.responseType) { 208 | mpRequestOption.responseType = config.responseType; 209 | } 210 | if (config.cancelToken) { 211 | // Handle cancellation 212 | config.cancelToken.promise.then(function onCanceled(cancel) { 213 | if (!requestTask) { 214 | return; 215 | } 216 | requestTask.abort(); 217 | reject(cancel); 218 | // Clean up request 219 | requestTask = undefined; 220 | }); 221 | } 222 | // Converting JSON strings to objects is handed over to the MiniPrograme 223 | if (isJSONstr(requestData)) { 224 | requestData = JSON.parse(requestData); 225 | } 226 | if (requestData !== undefined) { 227 | mpRequestOption.data = requestData; 228 | } 229 | requestTask = request(transformRequestOption(transformConfig(mpRequestOption))); 230 | }); 231 | } 232 | 233 | export default mpAdapter; 234 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * axios-miniprogram-adapter 0.3.5 (https://github.com/bigMeow/axios-miniprogram-adapter) 3 | * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md 4 | * Copyright 2018-2022 bigMeow. All Rights Reserved 5 | * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE) 6 | */ 7 | 8 | 'use strict'; 9 | 10 | function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } 11 | 12 | var utils = _interopDefault(require('axios/lib/utils')); 13 | var settle = _interopDefault(require('axios/lib/core/settle')); 14 | var buildURL = _interopDefault(require('axios/lib/helpers/buildURL')); 15 | var buildFullPath = _interopDefault(require('axios/lib/core/buildFullPath')); 16 | var createError = _interopDefault(require('axios/lib/core/createError')); 17 | 18 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 19 | // encoder 20 | function encoder(input) { 21 | var str = String(input); 22 | // initialize result and counter 23 | var block; 24 | var charCode; 25 | var idx = 0; 26 | var map = chars; 27 | var output = ''; 28 | for (; 29 | // if the next str index does not exist: 30 | // change the mapping table to "=" 31 | // check if d has no fractional digits 32 | str.charAt(idx | 0) || (map = '=', idx % 1); 33 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 34 | output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { 35 | charCode = str.charCodeAt(idx += 3 / 4); 36 | if (charCode > 0xFF) { 37 | throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); 38 | } 39 | block = block << 8 | charCode; 40 | } 41 | return output; 42 | } 43 | 44 | var platFormName = "wechat" /* 微信 */; 45 | /** 46 | * 获取各个平台的请求函数 47 | */ 48 | function getRequest() { 49 | switch (true) { 50 | case typeof wx === 'object': 51 | platFormName = "wechat" /* 微信 */; 52 | return wx.request.bind(wx); 53 | case typeof swan === 'object': 54 | platFormName = "baidu" /* 百度 */; 55 | return swan.request.bind(swan); 56 | case typeof dd === 'object': 57 | platFormName = "dd" /* 钉钉 */; 58 | // https://open.dingtalk.com/document/orgapp-client/send-network-requests 59 | return dd.httpRequest.bind(dd); 60 | case typeof my === 'object': 61 | /** 62 | * remark: 63 | * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。 64 | * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。 65 | * my.request的请求头默认值为{'content-type': 'application/json'}。 66 | * 还有个 dd.httpRequest 67 | */ 68 | platFormName = "alipay" /* 支付宝 */; 69 | return (my.request || my.httpRequest).bind(my); 70 | default: 71 | return wx.request.bind(wx); 72 | } 73 | } 74 | /** 75 | * 处理各平台返回的响应数据,抹平差异 76 | * @param mpResponse 77 | * @param config axios处理过的请求配置对象 78 | * @param request 小程序的调用发起请求时,传递给小程序api的实际配置 79 | */ 80 | function transformResponse(mpResponse, config, mpRequestOption) { 81 | var headers = mpResponse.header || mpResponse.headers; 82 | var status = mpResponse.statusCode || mpResponse.status; 83 | var statusText = ''; 84 | if (status === 200) { 85 | statusText = 'OK'; 86 | } 87 | else if (status === 400) { 88 | statusText = 'Bad Request'; 89 | } 90 | var response = { 91 | data: mpResponse.data, 92 | status: status, 93 | statusText: statusText, 94 | headers: headers, 95 | config: config, 96 | request: mpRequestOption 97 | }; 98 | return response; 99 | } 100 | /** 101 | * 处理各平台返回的错误信息,抹平差异 102 | * @param error 小程序api返回的错误对象 103 | * @param reject 上层的promise reject 函数 104 | * @param config 105 | */ 106 | function transformError(error, reject, config) { 107 | switch (platFormName) { 108 | case "wechat" /* 微信 */: 109 | if (error.errMsg.indexOf('request:fail abort') !== -1) { 110 | // Handle request cancellation (as opposed to a manual cancellation) 111 | reject(createError('Request aborted', config, 'ECONNABORTED', '')); 112 | } 113 | else if (error.errMsg.indexOf('timeout') !== -1) { 114 | // timeout 115 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '')); 116 | } 117 | else { 118 | // NetWordError 119 | reject(createError('Network Error', config, null, '')); 120 | } 121 | break; 122 | case "dd" /* 钉钉 */: 123 | case "alipay" /* 支付宝 */: 124 | // https://docs.alipay.com/mini/api/network 125 | if ([14, 19].includes(error.error)) { 126 | reject(createError('Request aborted', config, 'ECONNABORTED', '', error)); 127 | } 128 | else if ([13].includes(error.error)) { 129 | // timeout 130 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error)); 131 | } 132 | else { 133 | // NetWordError 134 | reject(createError('Network Error', config, null, '', error)); 135 | } 136 | break; 137 | case "baidu" /* 百度 */: 138 | // TODO error.errCode 139 | reject(createError('Network Error', config, null, '')); 140 | break; 141 | } 142 | } 143 | /** 144 | * 将axios的请求配置,转换成各个平台都支持的请求config 145 | * @param config 146 | */ 147 | function transformConfig(config) { 148 | var _a; 149 | if (["alipay" /* 支付宝 */, "dd" /* 钉钉 */].includes(platFormName)) { 150 | config.headers = config.header; 151 | delete config.header; 152 | if ("dd" /* 钉钉 */ === platFormName && config.method !== 'GET' && ((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') { 153 | // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化 154 | config.data = JSON.stringify(config.data); 155 | } 156 | } 157 | return config; 158 | } 159 | 160 | var isJSONstr = function (str) { 161 | try { 162 | return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]'; 163 | } 164 | catch (error) { 165 | return false; 166 | } 167 | }; 168 | function mpAdapter(config, _a) { 169 | var _b = (_a === void 0 ? {} : _a).transformRequestOption, transformRequestOption = _b === void 0 ? function (requestOption) { return requestOption; } : _b; 170 | var request = getRequest(); 171 | return new Promise(function (resolve, reject) { 172 | var requestTask; 173 | var requestData = config.data; 174 | var requestHeaders = config.headers; 175 | // baidu miniprogram only support upperCase 176 | var requestMethod = (config.method && config.method.toUpperCase()) || 'GET'; 177 | // miniprogram network request config 178 | var mpRequestOption = { 179 | method: requestMethod, 180 | url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer), 181 | timeout: config.timeout, 182 | // Listen for success 183 | success: function (mpResponse) { 184 | var response = transformResponse(mpResponse, config, mpRequestOption); 185 | settle(resolve, reject, response); 186 | }, 187 | // Handle request Exception 188 | fail: function (error) { 189 | transformError(error, reject, config); 190 | }, 191 | complete: function () { 192 | requestTask = undefined; 193 | } 194 | }; 195 | // HTTP basic authentication 196 | if (config.auth) { 197 | var _a = [config.auth.username || '', config.auth.password || ''], username = _a[0], password = _a[1]; 198 | requestHeaders.Authorization = 'Basic ' + encoder(username + ':' + password); 199 | } 200 | // Add headers to the request 201 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 202 | var _header = key.toLowerCase(); 203 | if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') { 204 | // Remove Content-Type if data is undefined 205 | // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer' 206 | delete requestHeaders[key]; 207 | } 208 | }); 209 | mpRequestOption.header = requestHeaders; 210 | // Add responseType to request if needed 211 | if (config.responseType) { 212 | mpRequestOption.responseType = config.responseType; 213 | } 214 | if (config.cancelToken) { 215 | // Handle cancellation 216 | config.cancelToken.promise.then(function onCanceled(cancel) { 217 | if (!requestTask) { 218 | return; 219 | } 220 | requestTask.abort(); 221 | reject(cancel); 222 | // Clean up request 223 | requestTask = undefined; 224 | }); 225 | } 226 | // Converting JSON strings to objects is handed over to the MiniPrograme 227 | if (isJSONstr(requestData)) { 228 | requestData = JSON.parse(requestData); 229 | } 230 | if (requestData !== undefined) { 231 | mpRequestOption.data = requestData; 232 | } 233 | requestTask = request(transformRequestOption(transformConfig(mpRequestOption))); 234 | }); 235 | } 236 | 237 | module.exports = mpAdapter; 238 | -------------------------------------------------------------------------------- /dist/index.aio.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * axios-miniprogram-adapter 0.3.5 (https://github.com/bigMeow/axios-miniprogram-adapter) 3 | * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md 4 | * Copyright 2018-2022 bigMeow. All Rights Reserved 5 | * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE) 6 | */ 7 | 8 | (function (global, factory) { 9 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('axios/lib/utils'), require('axios/lib/core/settle'), require('axios/lib/helpers/buildURL'), require('axios/lib/core/buildFullPath'), require('axios/lib/core/createError')) : 10 | typeof define === 'function' && define.amd ? define(['axios/lib/utils', 'axios/lib/core/settle', 'axios/lib/helpers/buildURL', 'axios/lib/core/buildFullPath', 'axios/lib/core/createError'], factory) : 11 | (global = global || self, global['axios-miniprogram-adapter'] = factory(global.utils, global.settle, global.buildURL, global.buildFullPath, global.createError)); 12 | }(this, (function (utils, settle, buildURL, buildFullPath, createError) { 'use strict'; 13 | 14 | utils = utils && Object.prototype.hasOwnProperty.call(utils, 'default') ? utils['default'] : utils; 15 | settle = settle && Object.prototype.hasOwnProperty.call(settle, 'default') ? settle['default'] : settle; 16 | buildURL = buildURL && Object.prototype.hasOwnProperty.call(buildURL, 'default') ? buildURL['default'] : buildURL; 17 | buildFullPath = buildFullPath && Object.prototype.hasOwnProperty.call(buildFullPath, 'default') ? buildFullPath['default'] : buildFullPath; 18 | createError = createError && Object.prototype.hasOwnProperty.call(createError, 'default') ? createError['default'] : createError; 19 | 20 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 21 | // encoder 22 | function encoder(input) { 23 | var str = String(input); 24 | // initialize result and counter 25 | var block; 26 | var charCode; 27 | var idx = 0; 28 | var map = chars; 29 | var output = ''; 30 | for (; 31 | // if the next str index does not exist: 32 | // change the mapping table to "=" 33 | // check if d has no fractional digits 34 | str.charAt(idx | 0) || (map = '=', idx % 1); 35 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 36 | output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { 37 | charCode = str.charCodeAt(idx += 3 / 4); 38 | if (charCode > 0xFF) { 39 | throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); 40 | } 41 | block = block << 8 | charCode; 42 | } 43 | return output; 44 | } 45 | 46 | var platFormName = "wechat" /* 微信 */; 47 | /** 48 | * 获取各个平台的请求函数 49 | */ 50 | function getRequest() { 51 | switch (true) { 52 | case typeof wx === 'object': 53 | platFormName = "wechat" /* 微信 */; 54 | return wx.request.bind(wx); 55 | case typeof swan === 'object': 56 | platFormName = "baidu" /* 百度 */; 57 | return swan.request.bind(swan); 58 | case typeof dd === 'object': 59 | platFormName = "dd" /* 钉钉 */; 60 | // https://open.dingtalk.com/document/orgapp-client/send-network-requests 61 | return dd.httpRequest.bind(dd); 62 | case typeof my === 'object': 63 | /** 64 | * remark: 65 | * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。 66 | * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。 67 | * my.request的请求头默认值为{'content-type': 'application/json'}。 68 | * 还有个 dd.httpRequest 69 | */ 70 | platFormName = "alipay" /* 支付宝 */; 71 | return (my.request || my.httpRequest).bind(my); 72 | default: 73 | return wx.request.bind(wx); 74 | } 75 | } 76 | /** 77 | * 处理各平台返回的响应数据,抹平差异 78 | * @param mpResponse 79 | * @param config axios处理过的请求配置对象 80 | * @param request 小程序的调用发起请求时,传递给小程序api的实际配置 81 | */ 82 | function transformResponse(mpResponse, config, mpRequestOption) { 83 | var headers = mpResponse.header || mpResponse.headers; 84 | var status = mpResponse.statusCode || mpResponse.status; 85 | var statusText = ''; 86 | if (status === 200) { 87 | statusText = 'OK'; 88 | } 89 | else if (status === 400) { 90 | statusText = 'Bad Request'; 91 | } 92 | var response = { 93 | data: mpResponse.data, 94 | status: status, 95 | statusText: statusText, 96 | headers: headers, 97 | config: config, 98 | request: mpRequestOption 99 | }; 100 | return response; 101 | } 102 | /** 103 | * 处理各平台返回的错误信息,抹平差异 104 | * @param error 小程序api返回的错误对象 105 | * @param reject 上层的promise reject 函数 106 | * @param config 107 | */ 108 | function transformError(error, reject, config) { 109 | switch (platFormName) { 110 | case "wechat" /* 微信 */: 111 | if (error.errMsg.indexOf('request:fail abort') !== -1) { 112 | // Handle request cancellation (as opposed to a manual cancellation) 113 | reject(createError('Request aborted', config, 'ECONNABORTED', '')); 114 | } 115 | else if (error.errMsg.indexOf('timeout') !== -1) { 116 | // timeout 117 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '')); 118 | } 119 | else { 120 | // NetWordError 121 | reject(createError('Network Error', config, null, '')); 122 | } 123 | break; 124 | case "dd" /* 钉钉 */: 125 | case "alipay" /* 支付宝 */: 126 | // https://docs.alipay.com/mini/api/network 127 | if ([14, 19].includes(error.error)) { 128 | reject(createError('Request aborted', config, 'ECONNABORTED', '', error)); 129 | } 130 | else if ([13].includes(error.error)) { 131 | // timeout 132 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error)); 133 | } 134 | else { 135 | // NetWordError 136 | reject(createError('Network Error', config, null, '', error)); 137 | } 138 | break; 139 | case "baidu" /* 百度 */: 140 | // TODO error.errCode 141 | reject(createError('Network Error', config, null, '')); 142 | break; 143 | } 144 | } 145 | /** 146 | * 将axios的请求配置,转换成各个平台都支持的请求config 147 | * @param config 148 | */ 149 | function transformConfig(config) { 150 | var _a; 151 | if (["alipay" /* 支付宝 */, "dd" /* 钉钉 */].includes(platFormName)) { 152 | config.headers = config.header; 153 | delete config.header; 154 | if ("dd" /* 钉钉 */ === platFormName && config.method !== 'GET' && ((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') { 155 | // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化 156 | config.data = JSON.stringify(config.data); 157 | } 158 | } 159 | return config; 160 | } 161 | 162 | var isJSONstr = function (str) { 163 | try { 164 | return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]'; 165 | } 166 | catch (error) { 167 | return false; 168 | } 169 | }; 170 | function mpAdapter(config, _a) { 171 | var _b = (_a === void 0 ? {} : _a).transformRequestOption, transformRequestOption = _b === void 0 ? function (requestOption) { return requestOption; } : _b; 172 | var request = getRequest(); 173 | return new Promise(function (resolve, reject) { 174 | var requestTask; 175 | var requestData = config.data; 176 | var requestHeaders = config.headers; 177 | // baidu miniprogram only support upperCase 178 | var requestMethod = (config.method && config.method.toUpperCase()) || 'GET'; 179 | // miniprogram network request config 180 | var mpRequestOption = { 181 | method: requestMethod, 182 | url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer), 183 | timeout: config.timeout, 184 | // Listen for success 185 | success: function (mpResponse) { 186 | var response = transformResponse(mpResponse, config, mpRequestOption); 187 | settle(resolve, reject, response); 188 | }, 189 | // Handle request Exception 190 | fail: function (error) { 191 | transformError(error, reject, config); 192 | }, 193 | complete: function () { 194 | requestTask = undefined; 195 | } 196 | }; 197 | // HTTP basic authentication 198 | if (config.auth) { 199 | var _a = [config.auth.username || '', config.auth.password || ''], username = _a[0], password = _a[1]; 200 | requestHeaders.Authorization = 'Basic ' + encoder(username + ':' + password); 201 | } 202 | // Add headers to the request 203 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 204 | var _header = key.toLowerCase(); 205 | if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') { 206 | // Remove Content-Type if data is undefined 207 | // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer' 208 | delete requestHeaders[key]; 209 | } 210 | }); 211 | mpRequestOption.header = requestHeaders; 212 | // Add responseType to request if needed 213 | if (config.responseType) { 214 | mpRequestOption.responseType = config.responseType; 215 | } 216 | if (config.cancelToken) { 217 | // Handle cancellation 218 | config.cancelToken.promise.then(function onCanceled(cancel) { 219 | if (!requestTask) { 220 | return; 221 | } 222 | requestTask.abort(); 223 | reject(cancel); 224 | // Clean up request 225 | requestTask = undefined; 226 | }); 227 | } 228 | // Converting JSON strings to objects is handed over to the MiniPrograme 229 | if (isJSONstr(requestData)) { 230 | requestData = JSON.parse(requestData); 231 | } 232 | if (requestData !== undefined) { 233 | mpRequestOption.data = requestData; 234 | } 235 | requestTask = request(transformRequestOption(transformConfig(mpRequestOption))); 236 | }); 237 | } 238 | 239 | return mpAdapter; 240 | 241 | }))); 242 | -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/follow-redirects/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["index.js","http.js","https.js"],"names":[],"mappings":";;;;;;;AAAA;AACA;AACA;ACFA,ADGA;ACFA,ADGA;AACA;AELA,AFMA;AELA,AFMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"index.js","sourcesContent":["var url = require(\"url\");\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar assert = require(\"assert\");\nvar Writable = require(\"stream\").Writable;\nvar debug = require(\"debug\")(\"follow-redirects\");\n\n// RFC7231§4.2.1: Of the request methods defined by this specification,\n// the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.\nvar SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true };\n\n// Create handlers that pass events from native requests\nvar eventHandlers = Object.create(null);\n[\"abort\", \"aborted\", \"error\", \"socket\", \"timeout\"].forEach(function (event) {\n eventHandlers[event] = function (arg) {\n this._redirectable.emit(event, arg);\n };\n});\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n options.headers = options.headers || {};\n this._options = options;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n self._processResponse(response);\n };\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Validate input and shift parameters if necessary\n if (!(typeof data === \"string\" || typeof data === \"object\" && (\"length\" in data))) {\n throw new Error(\"data should be a string, Buffer or Uint8Array\");\n }\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new Error(\"Request body larger than maxBodyLength limit\"));\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (typeof data === \"function\") {\n callback = data;\n data = encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Write data and end\n var currentRequest = this._currentRequest;\n this.write(data || \"\", encoding, function () {\n currentRequest.end(null, null, callback);\n });\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"abort\", \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\", \"setTimeout\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n this.emit(\"error\", new Error(\"Unsupported protocol \" + protocol));\n return;\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.substr(0, protocol.length - 1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n this._currentUrl = url.format(this._options);\n\n // Set up event handlers\n request._redirectable = this;\n for (var event in eventHandlers) {\n /* istanbul ignore else */\n if (event) {\n request.on(event, eventHandlers[event]);\n }\n }\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end.\n var i = 0;\n var buffers = this._requestBodyBuffers;\n (function writeNext() {\n if (i < buffers.length) {\n var buffer = buffers[i++];\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n else {\n request.end();\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: response.statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n var location = response.headers.location;\n if (location && this._options.followRedirects !== false &&\n response.statusCode >= 300 && response.statusCode < 400) {\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n this.emit(\"error\", new Error(\"Max redirects exceeded.\"));\n return;\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe […],\n // since the user might not wish to redirect an unsafe request.\n // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates\n // that the target resource resides temporarily under a different URI\n // and the user agent MUST NOT change the request method\n // if it performs an automatic redirection to that URI.\n var header;\n var headers = this._options.headers;\n if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n for (header in headers) {\n if (/^content-/i.test(header)) {\n delete headers[header];\n }\n }\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n if (!this._isRedirect) {\n for (header in headers) {\n if (/^host$/i.test(header)) {\n delete headers[header];\n }\n }\n }\n\n // Perform the redirected request\n var redirectUrl = url.resolve(this._currentUrl, location);\n debug(\"redirecting to\", redirectUrl);\n Object.assign(this._options, url.parse(redirectUrl));\n this._isRedirect = true;\n this._performRequest();\n\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n }\n else {\n // The response is not a redirect; return it as-is\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n }\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n wrappedProtocol.request = function (options, callback) {\n if (typeof options === \"string\") {\n options = url.parse(options);\n options.maxRedirects = exports.maxRedirects;\n }\n else {\n options = Object.assign({\n protocol: protocol,\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, options);\n }\n options.nativeProtocols = nativeProtocols;\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n };\n\n // Executes a GET request, following redirects\n wrappedProtocol.get = function (options, callback) {\n var request = wrappedProtocol.request(options, callback);\n request.end();\n return request;\n };\n });\n return exports;\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","module.exports = require(\"./\").http;\n","module.exports = require(\"./\").https;\n"]} -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/follow-redirects/index.js: -------------------------------------------------------------------------------- 1 | module.exports = (function() { 2 | var __MODS__ = {}; 3 | var __DEFINE__ = function(modId, func, req) { var m = { exports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; 4 | var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = { exports: {} }; __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); if(typeof m.exports === "object") { Object.keys(m.exports).forEach(function(k) { __MODS__[modId].m.exports[k] = m.exports[k]; }); if(m.exports.__esModule) Object.defineProperty(__MODS__[modId].m.exports, "__esModule", { value: true }); } else { __MODS__[modId].m.exports = m.exports; } } return __MODS__[modId].m.exports; }; 5 | var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; 6 | var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; 7 | __DEFINE__(1544589223614, function(require, module, exports) { 8 | var url = require("url"); 9 | var http = require("http"); 10 | var https = require("https"); 11 | var assert = require("assert"); 12 | var Writable = require("stream").Writable; 13 | var debug = require("debug")("follow-redirects"); 14 | 15 | // RFC7231§4.2.1: Of the request methods defined by this specification, 16 | // the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. 17 | var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true }; 18 | 19 | // Create handlers that pass events from native requests 20 | var eventHandlers = Object.create(null); 21 | ["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) { 22 | eventHandlers[event] = function (arg) { 23 | this._redirectable.emit(event, arg); 24 | }; 25 | }); 26 | 27 | // An HTTP(S) request that can be redirected 28 | function RedirectableRequest(options, responseCallback) { 29 | // Initialize the request 30 | Writable.call(this); 31 | options.headers = options.headers || {}; 32 | this._options = options; 33 | this._redirectCount = 0; 34 | this._redirects = []; 35 | this._requestBodyLength = 0; 36 | this._requestBodyBuffers = []; 37 | 38 | // Since http.request treats host as an alias of hostname, 39 | // but the url module interprets host as hostname plus port, 40 | // eliminate the host property to avoid confusion. 41 | if (options.host) { 42 | // Use hostname if set, because it has precedence 43 | if (!options.hostname) { 44 | options.hostname = options.host; 45 | } 46 | delete options.host; 47 | } 48 | 49 | // Attach a callback if passed 50 | if (responseCallback) { 51 | this.on("response", responseCallback); 52 | } 53 | 54 | // React to responses of native requests 55 | var self = this; 56 | this._onNativeResponse = function (response) { 57 | self._processResponse(response); 58 | }; 59 | 60 | // Complete the URL object when necessary 61 | if (!options.pathname && options.path) { 62 | var searchPos = options.path.indexOf("?"); 63 | if (searchPos < 0) { 64 | options.pathname = options.path; 65 | } 66 | else { 67 | options.pathname = options.path.substring(0, searchPos); 68 | options.search = options.path.substring(searchPos); 69 | } 70 | } 71 | 72 | // Perform the first request 73 | this._performRequest(); 74 | } 75 | RedirectableRequest.prototype = Object.create(Writable.prototype); 76 | 77 | // Writes buffered data to the current native request 78 | RedirectableRequest.prototype.write = function (data, encoding, callback) { 79 | // Validate input and shift parameters if necessary 80 | if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { 81 | throw new Error("data should be a string, Buffer or Uint8Array"); 82 | } 83 | if (typeof encoding === "function") { 84 | callback = encoding; 85 | encoding = null; 86 | } 87 | 88 | // Ignore empty buffers, since writing them doesn't invoke the callback 89 | // https://github.com/nodejs/node/issues/22066 90 | if (data.length === 0) { 91 | if (callback) { 92 | callback(); 93 | } 94 | return; 95 | } 96 | // Only write when we don't exceed the maximum body length 97 | if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { 98 | this._requestBodyLength += data.length; 99 | this._requestBodyBuffers.push({ data: data, encoding: encoding }); 100 | this._currentRequest.write(data, encoding, callback); 101 | } 102 | // Error when we exceed the maximum body length 103 | else { 104 | this.emit("error", new Error("Request body larger than maxBodyLength limit")); 105 | this.abort(); 106 | } 107 | }; 108 | 109 | // Ends the current native request 110 | RedirectableRequest.prototype.end = function (data, encoding, callback) { 111 | // Shift parameters if necessary 112 | if (typeof data === "function") { 113 | callback = data; 114 | data = encoding = null; 115 | } 116 | else if (typeof encoding === "function") { 117 | callback = encoding; 118 | encoding = null; 119 | } 120 | 121 | // Write data and end 122 | var currentRequest = this._currentRequest; 123 | this.write(data || "", encoding, function () { 124 | currentRequest.end(null, null, callback); 125 | }); 126 | }; 127 | 128 | // Sets a header value on the current native request 129 | RedirectableRequest.prototype.setHeader = function (name, value) { 130 | this._options.headers[name] = value; 131 | this._currentRequest.setHeader(name, value); 132 | }; 133 | 134 | // Clears a header value on the current native request 135 | RedirectableRequest.prototype.removeHeader = function (name) { 136 | delete this._options.headers[name]; 137 | this._currentRequest.removeHeader(name); 138 | }; 139 | 140 | // Proxy all other public ClientRequest methods 141 | [ 142 | "abort", "flushHeaders", "getHeader", 143 | "setNoDelay", "setSocketKeepAlive", "setTimeout", 144 | ].forEach(function (method) { 145 | RedirectableRequest.prototype[method] = function (a, b) { 146 | return this._currentRequest[method](a, b); 147 | }; 148 | }); 149 | 150 | // Proxy all public ClientRequest properties 151 | ["aborted", "connection", "socket"].forEach(function (property) { 152 | Object.defineProperty(RedirectableRequest.prototype, property, { 153 | get: function () { return this._currentRequest[property]; }, 154 | }); 155 | }); 156 | 157 | // Executes the next native request (initial or redirect) 158 | RedirectableRequest.prototype._performRequest = function () { 159 | // Load the native protocol 160 | var protocol = this._options.protocol; 161 | var nativeProtocol = this._options.nativeProtocols[protocol]; 162 | if (!nativeProtocol) { 163 | this.emit("error", new Error("Unsupported protocol " + protocol)); 164 | return; 165 | } 166 | 167 | // If specified, use the agent corresponding to the protocol 168 | // (HTTP and HTTPS use different types of agents) 169 | if (this._options.agents) { 170 | var scheme = protocol.substr(0, protocol.length - 1); 171 | this._options.agent = this._options.agents[scheme]; 172 | } 173 | 174 | // Create the native request 175 | var request = this._currentRequest = 176 | nativeProtocol.request(this._options, this._onNativeResponse); 177 | this._currentUrl = url.format(this._options); 178 | 179 | // Set up event handlers 180 | request._redirectable = this; 181 | for (var event in eventHandlers) { 182 | /* istanbul ignore else */ 183 | if (event) { 184 | request.on(event, eventHandlers[event]); 185 | } 186 | } 187 | 188 | // End a redirected request 189 | // (The first request must be ended explicitly with RedirectableRequest#end) 190 | if (this._isRedirect) { 191 | // Write the request entity and end. 192 | var i = 0; 193 | var buffers = this._requestBodyBuffers; 194 | (function writeNext() { 195 | if (i < buffers.length) { 196 | var buffer = buffers[i++]; 197 | request.write(buffer.data, buffer.encoding, writeNext); 198 | } 199 | else { 200 | request.end(); 201 | } 202 | }()); 203 | } 204 | }; 205 | 206 | // Processes a response from the current native request 207 | RedirectableRequest.prototype._processResponse = function (response) { 208 | // Store the redirected response 209 | if (this._options.trackRedirects) { 210 | this._redirects.push({ 211 | url: this._currentUrl, 212 | headers: response.headers, 213 | statusCode: response.statusCode, 214 | }); 215 | } 216 | 217 | // RFC7231§6.4: The 3xx (Redirection) class of status code indicates 218 | // that further action needs to be taken by the user agent in order to 219 | // fulfill the request. If a Location header field is provided, 220 | // the user agent MAY automatically redirect its request to the URI 221 | // referenced by the Location field value, 222 | // even if the specific status code is not understood. 223 | var location = response.headers.location; 224 | if (location && this._options.followRedirects !== false && 225 | response.statusCode >= 300 && response.statusCode < 400) { 226 | // RFC7231§6.4: A client SHOULD detect and intervene 227 | // in cyclical redirections (i.e., "infinite" redirection loops). 228 | if (++this._redirectCount > this._options.maxRedirects) { 229 | this.emit("error", new Error("Max redirects exceeded.")); 230 | return; 231 | } 232 | 233 | // RFC7231§6.4: Automatic redirection needs to done with 234 | // care for methods not known to be safe […], 235 | // since the user might not wish to redirect an unsafe request. 236 | // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates 237 | // that the target resource resides temporarily under a different URI 238 | // and the user agent MUST NOT change the request method 239 | // if it performs an automatic redirection to that URI. 240 | var header; 241 | var headers = this._options.headers; 242 | if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) { 243 | this._options.method = "GET"; 244 | // Drop a possible entity and headers related to it 245 | this._requestBodyBuffers = []; 246 | for (header in headers) { 247 | if (/^content-/i.test(header)) { 248 | delete headers[header]; 249 | } 250 | } 251 | } 252 | 253 | // Drop the Host header, as the redirect might lead to a different host 254 | if (!this._isRedirect) { 255 | for (header in headers) { 256 | if (/^host$/i.test(header)) { 257 | delete headers[header]; 258 | } 259 | } 260 | } 261 | 262 | // Perform the redirected request 263 | var redirectUrl = url.resolve(this._currentUrl, location); 264 | debug("redirecting to", redirectUrl); 265 | Object.assign(this._options, url.parse(redirectUrl)); 266 | this._isRedirect = true; 267 | this._performRequest(); 268 | 269 | // Discard the remainder of the response to avoid waiting for data 270 | response.destroy(); 271 | } 272 | else { 273 | // The response is not a redirect; return it as-is 274 | response.responseUrl = this._currentUrl; 275 | response.redirects = this._redirects; 276 | this.emit("response", response); 277 | 278 | // Clean up 279 | this._requestBodyBuffers = []; 280 | } 281 | }; 282 | 283 | // Wraps the key/value object of protocols with redirect functionality 284 | function wrap(protocols) { 285 | // Default settings 286 | var exports = { 287 | maxRedirects: 21, 288 | maxBodyLength: 10 * 1024 * 1024, 289 | }; 290 | 291 | // Wrap each protocol 292 | var nativeProtocols = {}; 293 | Object.keys(protocols).forEach(function (scheme) { 294 | var protocol = scheme + ":"; 295 | var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; 296 | var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); 297 | 298 | // Executes a request, following redirects 299 | wrappedProtocol.request = function (options, callback) { 300 | if (typeof options === "string") { 301 | options = url.parse(options); 302 | options.maxRedirects = exports.maxRedirects; 303 | } 304 | else { 305 | options = Object.assign({ 306 | protocol: protocol, 307 | maxRedirects: exports.maxRedirects, 308 | maxBodyLength: exports.maxBodyLength, 309 | }, options); 310 | } 311 | options.nativeProtocols = nativeProtocols; 312 | assert.equal(options.protocol, protocol, "protocol mismatch"); 313 | debug("options", options); 314 | return new RedirectableRequest(options, callback); 315 | }; 316 | 317 | // Executes a GET request, following redirects 318 | wrappedProtocol.get = function (options, callback) { 319 | var request = wrappedProtocol.request(options, callback); 320 | request.end(); 321 | return request; 322 | }; 323 | }); 324 | return exports; 325 | } 326 | 327 | // Exports 328 | module.exports = wrap({ http: http, https: https }); 329 | module.exports.wrap = wrap; 330 | 331 | }, function(modId) {var map = {"http":1544589223615,"https":1544589223616}; return __REQUIRE__(map[modId], modId); }) 332 | __DEFINE__(1544589223615, function(require, module, exports) { 333 | module.exports = require("./").http; 334 | 335 | }, function(modId) { var map = {"./":1544589223614}; return __REQUIRE__(map[modId], modId); }) 336 | __DEFINE__(1544589223616, function(require, module, exports) { 337 | module.exports = require("./").https; 338 | 339 | }, function(modId) { var map = {"./":1544589223614}; return __REQUIRE__(map[modId], modId); }) 340 | return __REQUIRE__(1544589223614); 341 | })() 342 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/debug/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["index.js","browser.js","debug.js","node.js"],"names":[],"mappings":";;;;;;;AAAA;AACA;AACA;ACFA,ADGA;ACFA,ADGA;ACFA,ADGA;ACFA,ACHA,AFMA;ACFA,ACHA,AFMA;ACFA,ACHA,AFMA;ACFA,ACHA,AFMA,AGTA;AFOA,ACHA,AFMA,AGTA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA,ACHA;AFOA,ACHA;ADIA,ACHA;ADIA,ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"index.js","sourcesContent":["/**\n * Detect Electron renderer process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer') {\n module.exports = require('./browser.js');\n} else {\n module.exports = require('./node.js');\n}\n","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',\n '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',\n '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',\n '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',\n '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',\n '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',\n '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',\n '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',\n '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',\n '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',\n '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * Active `debug` instances.\n */\nexports.instances = [];\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n var prevTime;\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n debug.destroy = destroy;\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n exports.instances.push(debug);\n\n return debug;\n}\n\nfunction destroy () {\n var index = exports.instances.indexOf(this);\n if (index !== -1) {\n exports.instances.splice(index, 1);\n return true;\n } else {\n return false;\n }\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var i;\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n\n for (i = 0; i < exports.instances.length; i++) {\n var instance = exports.instances[i];\n instance.enabled = exports.enabled(instance.namespace);\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n if (name[name.length - 1] === '*') {\n return true;\n }\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * Module dependencies.\n */\n\nvar tty = require('tty');\nvar util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\n\n/**\n * Colors.\n */\n\nexports.colors = [ 6, 2, 3, 4, 5, 1 ];\n\ntry {\n var supportsColor = require('supports-color');\n if (supportsColor && supportsColor.level >= 2) {\n exports.colors = [\n 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68,\n 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134,\n 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,\n 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204,\n 205, 206, 207, 208, 209, 214, 215, 220, 221\n ];\n }\n} catch (err) {\n // swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(function (key) {\n return /^debug_/i.test(key);\n}).reduce(function (obj, key) {\n // camel-case\n var prop = key\n .substring(6)\n .toLowerCase()\n .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });\n\n // coerce string value into JS value\n var val = process.env[key];\n if (/^(yes|on|true|enabled)$/i.test(val)) val = true;\n else if (/^(no|off|false|disabled)$/i.test(val)) val = false;\n else if (val === 'null') val = null;\n else val = Number(val);\n\n obj[prop] = val;\n return obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n return 'colors' in exports.inspectOpts\n ? Boolean(exports.inspectOpts.colors)\n : tty.isatty(process.stderr.fd);\n}\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nexports.formatters.o = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts)\n .split('\\n').map(function(str) {\n return str.trim()\n }).join(' ');\n};\n\n/**\n * Map %o to `util.inspect()`, allowing multiple lines if needed.\n */\n\nexports.formatters.O = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts);\n};\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var name = this.namespace;\n var useColors = this.useColors;\n\n if (useColors) {\n var c = this.color;\n var colorCode = '\\u001b[3' + (c < 8 ? c : '8;5;' + c);\n var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\\u001b[0m';\n\n args[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\\u001b[0m');\n } else {\n args[0] = getDate() + name + ' ' + args[0];\n }\n}\n\nfunction getDate() {\n if (exports.inspectOpts.hideDate) {\n return '';\n } else {\n return new Date().toISOString() + ' ';\n }\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log() {\n return process.stderr.write(util.format.apply(util, arguments) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n if (null == namespaces) {\n // If you set a process.env field to null or undefined, it gets cast to the\n // string 'null' or 'undefined'. Just delete instead.\n delete process.env.DEBUG;\n } else {\n process.env.DEBUG = namespaces;\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n return process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init (debug) {\n debug.inspectOpts = {};\n\n var keys = Object.keys(exports.inspectOpts);\n for (var i = 0; i < keys.length; i++) {\n debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n }\n}\n\n/**\n * Enable namespaces listed in `process.env.DEBUG` initially.\n */\n\nexports.enable(load());\n"]} -------------------------------------------------------------------------------- /demo/miniprograme-native/miniprogram_npm/debug/index.js: -------------------------------------------------------------------------------- 1 | module.exports = (function() { 2 | var __MODS__ = {}; 3 | var __DEFINE__ = function(modId, func, req) { var m = { exports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; }; 4 | var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = { exports: {} }; __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); if(typeof m.exports === "object") { Object.keys(m.exports).forEach(function(k) { __MODS__[modId].m.exports[k] = m.exports[k]; }); if(m.exports.__esModule) Object.defineProperty(__MODS__[modId].m.exports, "__esModule", { value: true }); } else { __MODS__[modId].m.exports = m.exports; } } return __MODS__[modId].m.exports; }; 5 | var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } }; 6 | var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; }; 7 | __DEFINE__(1544589223610, function(require, module, exports) { 8 | /** 9 | * Detect Electron renderer process, which is node, but we should 10 | * treat as a browser. 11 | */ 12 | 13 | if (typeof process === 'undefined' || process.type === 'renderer') { 14 | module.exports = require('./browser.js'); 15 | } else { 16 | module.exports = require('./node.js'); 17 | } 18 | 19 | }, function(modId) {var map = {"./browser.js":1544589223611,"./node.js":1544589223613}; return __REQUIRE__(map[modId], modId); }) 20 | __DEFINE__(1544589223611, function(require, module, exports) { 21 | /** 22 | * This is the web browser implementation of `debug()`. 23 | * 24 | * Expose `debug()` as the module. 25 | */ 26 | 27 | exports = module.exports = require('./debug'); 28 | exports.log = log; 29 | exports.formatArgs = formatArgs; 30 | exports.save = save; 31 | exports.load = load; 32 | exports.useColors = useColors; 33 | exports.storage = 'undefined' != typeof chrome 34 | && 'undefined' != typeof chrome.storage 35 | ? chrome.storage.local 36 | : localstorage(); 37 | 38 | /** 39 | * Colors. 40 | */ 41 | 42 | exports.colors = [ 43 | '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', 44 | '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', 45 | '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', 46 | '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', 47 | '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', 48 | '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', 49 | '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', 50 | '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', 51 | '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', 52 | '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', 53 | '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' 54 | ]; 55 | 56 | /** 57 | * Currently only WebKit-based Web Inspectors, Firefox >= v31, 58 | * and the Firebug extension (any Firefox version) are known 59 | * to support "%c" CSS customizations. 60 | * 61 | * TODO: add a `localStorage` variable to explicitly enable/disable colors 62 | */ 63 | 64 | function useColors() { 65 | // NB: In an Electron preload script, document will be defined but not fully 66 | // initialized. Since we know we're in Chrome, we'll just detect this case 67 | // explicitly 68 | if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { 69 | return true; 70 | } 71 | 72 | // Internet Explorer and Edge do not support colors. 73 | if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { 74 | return false; 75 | } 76 | 77 | // is webkit? http://stackoverflow.com/a/16459606/376773 78 | // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 79 | return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || 80 | // is firebug? http://stackoverflow.com/a/398120/376773 81 | (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || 82 | // is firefox >= v31? 83 | // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages 84 | (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || 85 | // double check webkit in userAgent just in case we are in a worker 86 | (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); 87 | } 88 | 89 | /** 90 | * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. 91 | */ 92 | 93 | exports.formatters.j = function(v) { 94 | try { 95 | return JSON.stringify(v); 96 | } catch (err) { 97 | return '[UnexpectedJSONParseError]: ' + err.message; 98 | } 99 | }; 100 | 101 | 102 | /** 103 | * Colorize log arguments if enabled. 104 | * 105 | * @api public 106 | */ 107 | 108 | function formatArgs(args) { 109 | var useColors = this.useColors; 110 | 111 | args[0] = (useColors ? '%c' : '') 112 | + this.namespace 113 | + (useColors ? ' %c' : ' ') 114 | + args[0] 115 | + (useColors ? '%c ' : ' ') 116 | + '+' + exports.humanize(this.diff); 117 | 118 | if (!useColors) return; 119 | 120 | var c = 'color: ' + this.color; 121 | args.splice(1, 0, c, 'color: inherit') 122 | 123 | // the final "%c" is somewhat tricky, because there could be other 124 | // arguments passed either before or after the %c, so we need to 125 | // figure out the correct index to insert the CSS into 126 | var index = 0; 127 | var lastC = 0; 128 | args[0].replace(/%[a-zA-Z%]/g, function(match) { 129 | if ('%%' === match) return; 130 | index++; 131 | if ('%c' === match) { 132 | // we only are interested in the *last* %c 133 | // (the user may have provided their own) 134 | lastC = index; 135 | } 136 | }); 137 | 138 | args.splice(lastC, 0, c); 139 | } 140 | 141 | /** 142 | * Invokes `console.log()` when available. 143 | * No-op when `console.log` is not a "function". 144 | * 145 | * @api public 146 | */ 147 | 148 | function log() { 149 | // this hackery is required for IE8/9, where 150 | // the `console.log` function doesn't have 'apply' 151 | return 'object' === typeof console 152 | && console.log 153 | && Function.prototype.apply.call(console.log, console, arguments); 154 | } 155 | 156 | /** 157 | * Save `namespaces`. 158 | * 159 | * @param {String} namespaces 160 | * @api private 161 | */ 162 | 163 | function save(namespaces) { 164 | try { 165 | if (null == namespaces) { 166 | exports.storage.removeItem('debug'); 167 | } else { 168 | exports.storage.debug = namespaces; 169 | } 170 | } catch(e) {} 171 | } 172 | 173 | /** 174 | * Load `namespaces`. 175 | * 176 | * @return {String} returns the previously persisted debug modes 177 | * @api private 178 | */ 179 | 180 | function load() { 181 | var r; 182 | try { 183 | r = exports.storage.debug; 184 | } catch(e) {} 185 | 186 | // If debug isn't set in LS, and we're in Electron, try to load $DEBUG 187 | if (!r && typeof process !== 'undefined' && 'env' in process) { 188 | r = process.env.DEBUG; 189 | } 190 | 191 | return r; 192 | } 193 | 194 | /** 195 | * Enable namespaces listed in `localStorage.debug` initially. 196 | */ 197 | 198 | exports.enable(load()); 199 | 200 | /** 201 | * Localstorage attempts to return the localstorage. 202 | * 203 | * This is necessary because safari throws 204 | * when a user disables cookies/localstorage 205 | * and you attempt to access it. 206 | * 207 | * @return {LocalStorage} 208 | * @api private 209 | */ 210 | 211 | function localstorage() { 212 | try { 213 | return window.localStorage; 214 | } catch (e) {} 215 | } 216 | 217 | }, function(modId) { var map = {"./debug":1544589223612}; return __REQUIRE__(map[modId], modId); }) 218 | __DEFINE__(1544589223612, function(require, module, exports) { 219 | 220 | /** 221 | * This is the common logic for both the Node.js and web browser 222 | * implementations of `debug()`. 223 | * 224 | * Expose `debug()` as the module. 225 | */ 226 | 227 | exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; 228 | exports.coerce = coerce; 229 | exports.disable = disable; 230 | exports.enable = enable; 231 | exports.enabled = enabled; 232 | exports.humanize = require('ms'); 233 | 234 | /** 235 | * Active `debug` instances. 236 | */ 237 | exports.instances = []; 238 | 239 | /** 240 | * The currently active debug mode names, and names to skip. 241 | */ 242 | 243 | exports.names = []; 244 | exports.skips = []; 245 | 246 | /** 247 | * Map of special "%n" handling functions, for the debug "format" argument. 248 | * 249 | * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". 250 | */ 251 | 252 | exports.formatters = {}; 253 | 254 | /** 255 | * Select a color. 256 | * @param {String} namespace 257 | * @return {Number} 258 | * @api private 259 | */ 260 | 261 | function selectColor(namespace) { 262 | var hash = 0, i; 263 | 264 | for (i in namespace) { 265 | hash = ((hash << 5) - hash) + namespace.charCodeAt(i); 266 | hash |= 0; // Convert to 32bit integer 267 | } 268 | 269 | return exports.colors[Math.abs(hash) % exports.colors.length]; 270 | } 271 | 272 | /** 273 | * Create a debugger with the given `namespace`. 274 | * 275 | * @param {String} namespace 276 | * @return {Function} 277 | * @api public 278 | */ 279 | 280 | function createDebug(namespace) { 281 | 282 | var prevTime; 283 | 284 | function debug() { 285 | // disabled? 286 | if (!debug.enabled) return; 287 | 288 | var self = debug; 289 | 290 | // set `diff` timestamp 291 | var curr = +new Date(); 292 | var ms = curr - (prevTime || curr); 293 | self.diff = ms; 294 | self.prev = prevTime; 295 | self.curr = curr; 296 | prevTime = curr; 297 | 298 | // turn the `arguments` into a proper Array 299 | var args = new Array(arguments.length); 300 | for (var i = 0; i < args.length; i++) { 301 | args[i] = arguments[i]; 302 | } 303 | 304 | args[0] = exports.coerce(args[0]); 305 | 306 | if ('string' !== typeof args[0]) { 307 | // anything else let's inspect with %O 308 | args.unshift('%O'); 309 | } 310 | 311 | // apply any `formatters` transformations 312 | var index = 0; 313 | args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { 314 | // if we encounter an escaped % then don't increase the array index 315 | if (match === '%%') return match; 316 | index++; 317 | var formatter = exports.formatters[format]; 318 | if ('function' === typeof formatter) { 319 | var val = args[index]; 320 | match = formatter.call(self, val); 321 | 322 | // now we need to remove `args[index]` since it's inlined in the `format` 323 | args.splice(index, 1); 324 | index--; 325 | } 326 | return match; 327 | }); 328 | 329 | // apply env-specific formatting (colors, etc.) 330 | exports.formatArgs.call(self, args); 331 | 332 | var logFn = debug.log || exports.log || console.log.bind(console); 333 | logFn.apply(self, args); 334 | } 335 | 336 | debug.namespace = namespace; 337 | debug.enabled = exports.enabled(namespace); 338 | debug.useColors = exports.useColors(); 339 | debug.color = selectColor(namespace); 340 | debug.destroy = destroy; 341 | 342 | // env-specific initialization logic for debug instances 343 | if ('function' === typeof exports.init) { 344 | exports.init(debug); 345 | } 346 | 347 | exports.instances.push(debug); 348 | 349 | return debug; 350 | } 351 | 352 | function destroy () { 353 | var index = exports.instances.indexOf(this); 354 | if (index !== -1) { 355 | exports.instances.splice(index, 1); 356 | return true; 357 | } else { 358 | return false; 359 | } 360 | } 361 | 362 | /** 363 | * Enables a debug mode by namespaces. This can include modes 364 | * separated by a colon and wildcards. 365 | * 366 | * @param {String} namespaces 367 | * @api public 368 | */ 369 | 370 | function enable(namespaces) { 371 | exports.save(namespaces); 372 | 373 | exports.names = []; 374 | exports.skips = []; 375 | 376 | var i; 377 | var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); 378 | var len = split.length; 379 | 380 | for (i = 0; i < len; i++) { 381 | if (!split[i]) continue; // ignore empty strings 382 | namespaces = split[i].replace(/\*/g, '.*?'); 383 | if (namespaces[0] === '-') { 384 | exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); 385 | } else { 386 | exports.names.push(new RegExp('^' + namespaces + '$')); 387 | } 388 | } 389 | 390 | for (i = 0; i < exports.instances.length; i++) { 391 | var instance = exports.instances[i]; 392 | instance.enabled = exports.enabled(instance.namespace); 393 | } 394 | } 395 | 396 | /** 397 | * Disable debug output. 398 | * 399 | * @api public 400 | */ 401 | 402 | function disable() { 403 | exports.enable(''); 404 | } 405 | 406 | /** 407 | * Returns true if the given mode name is enabled, false otherwise. 408 | * 409 | * @param {String} name 410 | * @return {Boolean} 411 | * @api public 412 | */ 413 | 414 | function enabled(name) { 415 | if (name[name.length - 1] === '*') { 416 | return true; 417 | } 418 | var i, len; 419 | for (i = 0, len = exports.skips.length; i < len; i++) { 420 | if (exports.skips[i].test(name)) { 421 | return false; 422 | } 423 | } 424 | for (i = 0, len = exports.names.length; i < len; i++) { 425 | if (exports.names[i].test(name)) { 426 | return true; 427 | } 428 | } 429 | return false; 430 | } 431 | 432 | /** 433 | * Coerce `val`. 434 | * 435 | * @param {Mixed} val 436 | * @return {Mixed} 437 | * @api private 438 | */ 439 | 440 | function coerce(val) { 441 | if (val instanceof Error) return val.stack || val.message; 442 | return val; 443 | } 444 | 445 | }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); }) 446 | __DEFINE__(1544589223613, function(require, module, exports) { 447 | /** 448 | * Module dependencies. 449 | */ 450 | 451 | var tty = require('tty'); 452 | var util = require('util'); 453 | 454 | /** 455 | * This is the Node.js implementation of `debug()`. 456 | * 457 | * Expose `debug()` as the module. 458 | */ 459 | 460 | exports = module.exports = require('./debug'); 461 | exports.init = init; 462 | exports.log = log; 463 | exports.formatArgs = formatArgs; 464 | exports.save = save; 465 | exports.load = load; 466 | exports.useColors = useColors; 467 | 468 | /** 469 | * Colors. 470 | */ 471 | 472 | exports.colors = [ 6, 2, 3, 4, 5, 1 ]; 473 | 474 | try { 475 | var supportsColor = require('supports-color'); 476 | if (supportsColor && supportsColor.level >= 2) { 477 | exports.colors = [ 478 | 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 479 | 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 480 | 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 481 | 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 482 | 205, 206, 207, 208, 209, 214, 215, 220, 221 483 | ]; 484 | } 485 | } catch (err) { 486 | // swallow - we only care if `supports-color` is available; it doesn't have to be. 487 | } 488 | 489 | /** 490 | * Build up the default `inspectOpts` object from the environment variables. 491 | * 492 | * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js 493 | */ 494 | 495 | exports.inspectOpts = Object.keys(process.env).filter(function (key) { 496 | return /^debug_/i.test(key); 497 | }).reduce(function (obj, key) { 498 | // camel-case 499 | var prop = key 500 | .substring(6) 501 | .toLowerCase() 502 | .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); 503 | 504 | // coerce string value into JS value 505 | var val = process.env[key]; 506 | if (/^(yes|on|true|enabled)$/i.test(val)) val = true; 507 | else if (/^(no|off|false|disabled)$/i.test(val)) val = false; 508 | else if (val === 'null') val = null; 509 | else val = Number(val); 510 | 511 | obj[prop] = val; 512 | return obj; 513 | }, {}); 514 | 515 | /** 516 | * Is stdout a TTY? Colored output is enabled when `true`. 517 | */ 518 | 519 | function useColors() { 520 | return 'colors' in exports.inspectOpts 521 | ? Boolean(exports.inspectOpts.colors) 522 | : tty.isatty(process.stderr.fd); 523 | } 524 | 525 | /** 526 | * Map %o to `util.inspect()`, all on a single line. 527 | */ 528 | 529 | exports.formatters.o = function(v) { 530 | this.inspectOpts.colors = this.useColors; 531 | return util.inspect(v, this.inspectOpts) 532 | .split('\n').map(function(str) { 533 | return str.trim() 534 | }).join(' '); 535 | }; 536 | 537 | /** 538 | * Map %o to `util.inspect()`, allowing multiple lines if needed. 539 | */ 540 | 541 | exports.formatters.O = function(v) { 542 | this.inspectOpts.colors = this.useColors; 543 | return util.inspect(v, this.inspectOpts); 544 | }; 545 | 546 | /** 547 | * Adds ANSI color escape codes if enabled. 548 | * 549 | * @api public 550 | */ 551 | 552 | function formatArgs(args) { 553 | var name = this.namespace; 554 | var useColors = this.useColors; 555 | 556 | if (useColors) { 557 | var c = this.color; 558 | var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); 559 | var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; 560 | 561 | args[0] = prefix + args[0].split('\n').join('\n' + prefix); 562 | args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); 563 | } else { 564 | args[0] = getDate() + name + ' ' + args[0]; 565 | } 566 | } 567 | 568 | function getDate() { 569 | if (exports.inspectOpts.hideDate) { 570 | return ''; 571 | } else { 572 | return new Date().toISOString() + ' '; 573 | } 574 | } 575 | 576 | /** 577 | * Invokes `util.format()` with the specified arguments and writes to stderr. 578 | */ 579 | 580 | function log() { 581 | return process.stderr.write(util.format.apply(util, arguments) + '\n'); 582 | } 583 | 584 | /** 585 | * Save `namespaces`. 586 | * 587 | * @param {String} namespaces 588 | * @api private 589 | */ 590 | 591 | function save(namespaces) { 592 | if (null == namespaces) { 593 | // If you set a process.env field to null or undefined, it gets cast to the 594 | // string 'null' or 'undefined'. Just delete instead. 595 | delete process.env.DEBUG; 596 | } else { 597 | process.env.DEBUG = namespaces; 598 | } 599 | } 600 | 601 | /** 602 | * Load `namespaces`. 603 | * 604 | * @return {String} returns the previously persisted debug modes 605 | * @api private 606 | */ 607 | 608 | function load() { 609 | return process.env.DEBUG; 610 | } 611 | 612 | /** 613 | * Init logic for `debug` instances. 614 | * 615 | * Create a new `inspectOpts` object in case `useColors` is set 616 | * differently for a particular `debug` instance. 617 | */ 618 | 619 | function init (debug) { 620 | debug.inspectOpts = {}; 621 | 622 | var keys = Object.keys(exports.inspectOpts); 623 | for (var i = 0; i < keys.length; i++) { 624 | debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; 625 | } 626 | } 627 | 628 | /** 629 | * Enable namespaces listed in `process.env.DEBUG` initially. 630 | */ 631 | 632 | exports.enable(load()); 633 | 634 | }, function(modId) { var map = {"./debug":1544589223612}; return __REQUIRE__(map[modId], modId); }) 635 | return __REQUIRE__(1544589223610); 636 | })() 637 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /dist/miniprogram/index.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * axios-miniprogram-adapter 0.3.5 (https://github.com/bigMeow/axios-miniprogram-adapter) 3 | * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md 4 | * Copyright 2018-2022 bigMeow. All Rights Reserved 5 | * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE) 6 | */ 7 | 8 | 'use strict'; 9 | 10 | var bind = function bind(fn, thisArg) { 11 | return function wrap() { 12 | var args = new Array(arguments.length); 13 | for (var i = 0; i < args.length; i++) { 14 | args[i] = arguments[i]; 15 | } 16 | return fn.apply(thisArg, args); 17 | }; 18 | }; 19 | 20 | /*global toString:true*/ 21 | 22 | // utils is a library of generic helper functions non-specific to axios 23 | 24 | var toString = Object.prototype.toString; 25 | 26 | /** 27 | * Determine if a value is an Array 28 | * 29 | * @param {Object} val The value to test 30 | * @returns {boolean} True if value is an Array, otherwise false 31 | */ 32 | function isArray(val) { 33 | return toString.call(val) === '[object Array]'; 34 | } 35 | 36 | /** 37 | * Determine if a value is undefined 38 | * 39 | * @param {Object} val The value to test 40 | * @returns {boolean} True if the value is undefined, otherwise false 41 | */ 42 | function isUndefined(val) { 43 | return typeof val === 'undefined'; 44 | } 45 | 46 | /** 47 | * Determine if a value is a Buffer 48 | * 49 | * @param {Object} val The value to test 50 | * @returns {boolean} True if value is a Buffer, otherwise false 51 | */ 52 | function isBuffer(val) { 53 | return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) 54 | && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); 55 | } 56 | 57 | /** 58 | * Determine if a value is an ArrayBuffer 59 | * 60 | * @param {Object} val The value to test 61 | * @returns {boolean} True if value is an ArrayBuffer, otherwise false 62 | */ 63 | function isArrayBuffer(val) { 64 | return toString.call(val) === '[object ArrayBuffer]'; 65 | } 66 | 67 | /** 68 | * Determine if a value is a FormData 69 | * 70 | * @param {Object} val The value to test 71 | * @returns {boolean} True if value is an FormData, otherwise false 72 | */ 73 | function isFormData(val) { 74 | return (typeof FormData !== 'undefined') && (val instanceof FormData); 75 | } 76 | 77 | /** 78 | * Determine if a value is a view on an ArrayBuffer 79 | * 80 | * @param {Object} val The value to test 81 | * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false 82 | */ 83 | function isArrayBufferView(val) { 84 | var result; 85 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { 86 | result = ArrayBuffer.isView(val); 87 | } else { 88 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); 89 | } 90 | return result; 91 | } 92 | 93 | /** 94 | * Determine if a value is a String 95 | * 96 | * @param {Object} val The value to test 97 | * @returns {boolean} True if value is a String, otherwise false 98 | */ 99 | function isString(val) { 100 | return typeof val === 'string'; 101 | } 102 | 103 | /** 104 | * Determine if a value is a Number 105 | * 106 | * @param {Object} val The value to test 107 | * @returns {boolean} True if value is a Number, otherwise false 108 | */ 109 | function isNumber(val) { 110 | return typeof val === 'number'; 111 | } 112 | 113 | /** 114 | * Determine if a value is an Object 115 | * 116 | * @param {Object} val The value to test 117 | * @returns {boolean} True if value is an Object, otherwise false 118 | */ 119 | function isObject(val) { 120 | return val !== null && typeof val === 'object'; 121 | } 122 | 123 | /** 124 | * Determine if a value is a Date 125 | * 126 | * @param {Object} val The value to test 127 | * @returns {boolean} True if value is a Date, otherwise false 128 | */ 129 | function isDate(val) { 130 | return toString.call(val) === '[object Date]'; 131 | } 132 | 133 | /** 134 | * Determine if a value is a File 135 | * 136 | * @param {Object} val The value to test 137 | * @returns {boolean} True if value is a File, otherwise false 138 | */ 139 | function isFile(val) { 140 | return toString.call(val) === '[object File]'; 141 | } 142 | 143 | /** 144 | * Determine if a value is a Blob 145 | * 146 | * @param {Object} val The value to test 147 | * @returns {boolean} True if value is a Blob, otherwise false 148 | */ 149 | function isBlob(val) { 150 | return toString.call(val) === '[object Blob]'; 151 | } 152 | 153 | /** 154 | * Determine if a value is a Function 155 | * 156 | * @param {Object} val The value to test 157 | * @returns {boolean} True if value is a Function, otherwise false 158 | */ 159 | function isFunction(val) { 160 | return toString.call(val) === '[object Function]'; 161 | } 162 | 163 | /** 164 | * Determine if a value is a Stream 165 | * 166 | * @param {Object} val The value to test 167 | * @returns {boolean} True if value is a Stream, otherwise false 168 | */ 169 | function isStream(val) { 170 | return isObject(val) && isFunction(val.pipe); 171 | } 172 | 173 | /** 174 | * Determine if a value is a URLSearchParams object 175 | * 176 | * @param {Object} val The value to test 177 | * @returns {boolean} True if value is a URLSearchParams object, otherwise false 178 | */ 179 | function isURLSearchParams(val) { 180 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; 181 | } 182 | 183 | /** 184 | * Trim excess whitespace off the beginning and end of a string 185 | * 186 | * @param {String} str The String to trim 187 | * @returns {String} The String freed of excess whitespace 188 | */ 189 | function trim(str) { 190 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); 191 | } 192 | 193 | /** 194 | * Determine if we're running in a standard browser environment 195 | * 196 | * This allows axios to run in a web worker, and react-native. 197 | * Both environments support XMLHttpRequest, but not fully standard globals. 198 | * 199 | * web workers: 200 | * typeof window -> undefined 201 | * typeof document -> undefined 202 | * 203 | * react-native: 204 | * navigator.product -> 'ReactNative' 205 | * nativescript 206 | * navigator.product -> 'NativeScript' or 'NS' 207 | */ 208 | function isStandardBrowserEnv() { 209 | if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || 210 | navigator.product === 'NativeScript' || 211 | navigator.product === 'NS')) { 212 | return false; 213 | } 214 | return ( 215 | typeof window !== 'undefined' && 216 | typeof document !== 'undefined' 217 | ); 218 | } 219 | 220 | /** 221 | * Iterate over an Array or an Object invoking a function for each item. 222 | * 223 | * If `obj` is an Array callback will be called passing 224 | * the value, index, and complete array for each item. 225 | * 226 | * If 'obj' is an Object callback will be called passing 227 | * the value, key, and complete object for each property. 228 | * 229 | * @param {Object|Array} obj The object to iterate 230 | * @param {Function} fn The callback to invoke for each item 231 | */ 232 | function forEach(obj, fn) { 233 | // Don't bother if no value provided 234 | if (obj === null || typeof obj === 'undefined') { 235 | return; 236 | } 237 | 238 | // Force an array if not already something iterable 239 | if (typeof obj !== 'object') { 240 | /*eslint no-param-reassign:0*/ 241 | obj = [obj]; 242 | } 243 | 244 | if (isArray(obj)) { 245 | // Iterate over array values 246 | for (var i = 0, l = obj.length; i < l; i++) { 247 | fn.call(null, obj[i], i, obj); 248 | } 249 | } else { 250 | // Iterate over object keys 251 | for (var key in obj) { 252 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 253 | fn.call(null, obj[key], key, obj); 254 | } 255 | } 256 | } 257 | } 258 | 259 | /** 260 | * Accepts varargs expecting each argument to be an object, then 261 | * immutably merges the properties of each object and returns result. 262 | * 263 | * When multiple objects contain the same key the later object in 264 | * the arguments list will take precedence. 265 | * 266 | * Example: 267 | * 268 | * ```js 269 | * var result = merge({foo: 123}, {foo: 456}); 270 | * console.log(result.foo); // outputs 456 271 | * ``` 272 | * 273 | * @param {Object} obj1 Object to merge 274 | * @returns {Object} Result of all merge properties 275 | */ 276 | function merge(/* obj1, obj2, obj3, ... */) { 277 | var result = {}; 278 | function assignValue(val, key) { 279 | if (typeof result[key] === 'object' && typeof val === 'object') { 280 | result[key] = merge(result[key], val); 281 | } else { 282 | result[key] = val; 283 | } 284 | } 285 | 286 | for (var i = 0, l = arguments.length; i < l; i++) { 287 | forEach(arguments[i], assignValue); 288 | } 289 | return result; 290 | } 291 | 292 | /** 293 | * Function equal to merge with the difference being that no reference 294 | * to original objects is kept. 295 | * 296 | * @see merge 297 | * @param {Object} obj1 Object to merge 298 | * @returns {Object} Result of all merge properties 299 | */ 300 | function deepMerge(/* obj1, obj2, obj3, ... */) { 301 | var result = {}; 302 | function assignValue(val, key) { 303 | if (typeof result[key] === 'object' && typeof val === 'object') { 304 | result[key] = deepMerge(result[key], val); 305 | } else if (typeof val === 'object') { 306 | result[key] = deepMerge({}, val); 307 | } else { 308 | result[key] = val; 309 | } 310 | } 311 | 312 | for (var i = 0, l = arguments.length; i < l; i++) { 313 | forEach(arguments[i], assignValue); 314 | } 315 | return result; 316 | } 317 | 318 | /** 319 | * Extends object a by mutably adding to it the properties of object b. 320 | * 321 | * @param {Object} a The object to be extended 322 | * @param {Object} b The object to copy properties from 323 | * @param {Object} thisArg The object to bind function to 324 | * @return {Object} The resulting value of object a 325 | */ 326 | function extend(a, b, thisArg) { 327 | forEach(b, function assignValue(val, key) { 328 | if (thisArg && typeof val === 'function') { 329 | a[key] = bind(val, thisArg); 330 | } else { 331 | a[key] = val; 332 | } 333 | }); 334 | return a; 335 | } 336 | 337 | var utils = { 338 | isArray: isArray, 339 | isArrayBuffer: isArrayBuffer, 340 | isBuffer: isBuffer, 341 | isFormData: isFormData, 342 | isArrayBufferView: isArrayBufferView, 343 | isString: isString, 344 | isNumber: isNumber, 345 | isObject: isObject, 346 | isUndefined: isUndefined, 347 | isDate: isDate, 348 | isFile: isFile, 349 | isBlob: isBlob, 350 | isFunction: isFunction, 351 | isStream: isStream, 352 | isURLSearchParams: isURLSearchParams, 353 | isStandardBrowserEnv: isStandardBrowserEnv, 354 | forEach: forEach, 355 | merge: merge, 356 | deepMerge: deepMerge, 357 | extend: extend, 358 | trim: trim 359 | }; 360 | 361 | /** 362 | * Update an Error with the specified config, error code, and response. 363 | * 364 | * @param {Error} error The error to update. 365 | * @param {Object} config The config. 366 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 367 | * @param {Object} [request] The request. 368 | * @param {Object} [response] The response. 369 | * @returns {Error} The error. 370 | */ 371 | var enhanceError = function enhanceError(error, config, code, request, response) { 372 | error.config = config; 373 | if (code) { 374 | error.code = code; 375 | } 376 | 377 | error.request = request; 378 | error.response = response; 379 | error.isAxiosError = true; 380 | 381 | error.toJSON = function() { 382 | return { 383 | // Standard 384 | message: this.message, 385 | name: this.name, 386 | // Microsoft 387 | description: this.description, 388 | number: this.number, 389 | // Mozilla 390 | fileName: this.fileName, 391 | lineNumber: this.lineNumber, 392 | columnNumber: this.columnNumber, 393 | stack: this.stack, 394 | // Axios 395 | config: this.config, 396 | code: this.code 397 | }; 398 | }; 399 | return error; 400 | }; 401 | 402 | /** 403 | * Create an Error with the specified message, config, error code, request and response. 404 | * 405 | * @param {string} message The error message. 406 | * @param {Object} config The config. 407 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 408 | * @param {Object} [request] The request. 409 | * @param {Object} [response] The response. 410 | * @returns {Error} The created error. 411 | */ 412 | var createError = function createError(message, config, code, request, response) { 413 | var error = new Error(message); 414 | return enhanceError(error, config, code, request, response); 415 | }; 416 | 417 | /** 418 | * Resolve or reject a Promise based on response status. 419 | * 420 | * @param {Function} resolve A function that resolves the promise. 421 | * @param {Function} reject A function that rejects the promise. 422 | * @param {object} response The response. 423 | */ 424 | var settle = function settle(resolve, reject, response) { 425 | var validateStatus = response.config.validateStatus; 426 | if (!validateStatus || validateStatus(response.status)) { 427 | resolve(response); 428 | } else { 429 | reject(createError( 430 | 'Request failed with status code ' + response.status, 431 | response.config, 432 | null, 433 | response.request, 434 | response 435 | )); 436 | } 437 | }; 438 | 439 | function encode(val) { 440 | return encodeURIComponent(val). 441 | replace(/%40/gi, '@'). 442 | replace(/%3A/gi, ':'). 443 | replace(/%24/g, '$'). 444 | replace(/%2C/gi, ','). 445 | replace(/%20/g, '+'). 446 | replace(/%5B/gi, '['). 447 | replace(/%5D/gi, ']'); 448 | } 449 | 450 | /** 451 | * Build a URL by appending params to the end 452 | * 453 | * @param {string} url The base of the url (e.g., http://www.google.com) 454 | * @param {object} [params] The params to be appended 455 | * @returns {string} The formatted url 456 | */ 457 | var buildURL = function buildURL(url, params, paramsSerializer) { 458 | /*eslint no-param-reassign:0*/ 459 | if (!params) { 460 | return url; 461 | } 462 | 463 | var serializedParams; 464 | if (paramsSerializer) { 465 | serializedParams = paramsSerializer(params); 466 | } else if (utils.isURLSearchParams(params)) { 467 | serializedParams = params.toString(); 468 | } else { 469 | var parts = []; 470 | 471 | utils.forEach(params, function serialize(val, key) { 472 | if (val === null || typeof val === 'undefined') { 473 | return; 474 | } 475 | 476 | if (utils.isArray(val)) { 477 | key = key + '[]'; 478 | } else { 479 | val = [val]; 480 | } 481 | 482 | utils.forEach(val, function parseValue(v) { 483 | if (utils.isDate(v)) { 484 | v = v.toISOString(); 485 | } else if (utils.isObject(v)) { 486 | v = JSON.stringify(v); 487 | } 488 | parts.push(encode(key) + '=' + encode(v)); 489 | }); 490 | }); 491 | 492 | serializedParams = parts.join('&'); 493 | } 494 | 495 | if (serializedParams) { 496 | var hashmarkIndex = url.indexOf('#'); 497 | if (hashmarkIndex !== -1) { 498 | url = url.slice(0, hashmarkIndex); 499 | } 500 | 501 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; 502 | } 503 | 504 | return url; 505 | }; 506 | 507 | /** 508 | * Determines whether the specified URL is absolute 509 | * 510 | * @param {string} url The URL to test 511 | * @returns {boolean} True if the specified URL is absolute, otherwise false 512 | */ 513 | var isAbsoluteURL = function isAbsoluteURL(url) { 514 | // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). 515 | // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed 516 | // by any combination of letters, digits, plus, period, or hyphen. 517 | return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); 518 | }; 519 | 520 | /** 521 | * Creates a new URL by combining the specified URLs 522 | * 523 | * @param {string} baseURL The base URL 524 | * @param {string} relativeURL The relative URL 525 | * @returns {string} The combined URL 526 | */ 527 | var combineURLs = function combineURLs(baseURL, relativeURL) { 528 | return relativeURL 529 | ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') 530 | : baseURL; 531 | }; 532 | 533 | /** 534 | * Creates a new URL by combining the baseURL with the requestedURL, 535 | * only when the requestedURL is not already an absolute URL. 536 | * If the requestURL is absolute, this function returns the requestedURL untouched. 537 | * 538 | * @param {string} baseURL The base URL 539 | * @param {string} requestedURL Absolute or relative URL to combine 540 | * @returns {string} The combined full path 541 | */ 542 | var buildFullPath = function buildFullPath(baseURL, requestedURL) { 543 | if (baseURL && !isAbsoluteURL(requestedURL)) { 544 | return combineURLs(baseURL, requestedURL); 545 | } 546 | return requestedURL; 547 | }; 548 | 549 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 550 | // encoder 551 | function encoder(input) { 552 | var str = String(input); 553 | // initialize result and counter 554 | var block; 555 | var charCode; 556 | var idx = 0; 557 | var map = chars; 558 | var output = ''; 559 | for (; 560 | // if the next str index does not exist: 561 | // change the mapping table to "=" 562 | // check if d has no fractional digits 563 | str.charAt(idx | 0) || (map = '=', idx % 1); 564 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 565 | output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { 566 | charCode = str.charCodeAt(idx += 3 / 4); 567 | if (charCode > 0xFF) { 568 | throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); 569 | } 570 | block = block << 8 | charCode; 571 | } 572 | return output; 573 | } 574 | 575 | var platFormName = "wechat" /* 微信 */; 576 | /** 577 | * 获取各个平台的请求函数 578 | */ 579 | function getRequest() { 580 | switch (true) { 581 | case typeof wx === 'object': 582 | platFormName = "wechat" /* 微信 */; 583 | return wx.request.bind(wx); 584 | case typeof swan === 'object': 585 | platFormName = "baidu" /* 百度 */; 586 | return swan.request.bind(swan); 587 | case typeof dd === 'object': 588 | platFormName = "dd" /* 钉钉 */; 589 | // https://open.dingtalk.com/document/orgapp-client/send-network-requests 590 | return dd.httpRequest.bind(dd); 591 | case typeof my === 'object': 592 | /** 593 | * remark: 594 | * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。 595 | * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。 596 | * my.request的请求头默认值为{'content-type': 'application/json'}。 597 | * 还有个 dd.httpRequest 598 | */ 599 | platFormName = "alipay" /* 支付宝 */; 600 | return (my.request || my.httpRequest).bind(my); 601 | default: 602 | return wx.request.bind(wx); 603 | } 604 | } 605 | /** 606 | * 处理各平台返回的响应数据,抹平差异 607 | * @param mpResponse 608 | * @param config axios处理过的请求配置对象 609 | * @param request 小程序的调用发起请求时,传递给小程序api的实际配置 610 | */ 611 | function transformResponse(mpResponse, config, mpRequestOption) { 612 | var headers = mpResponse.header || mpResponse.headers; 613 | var status = mpResponse.statusCode || mpResponse.status; 614 | var statusText = ''; 615 | if (status === 200) { 616 | statusText = 'OK'; 617 | } 618 | else if (status === 400) { 619 | statusText = 'Bad Request'; 620 | } 621 | var response = { 622 | data: mpResponse.data, 623 | status: status, 624 | statusText: statusText, 625 | headers: headers, 626 | config: config, 627 | request: mpRequestOption 628 | }; 629 | return response; 630 | } 631 | /** 632 | * 处理各平台返回的错误信息,抹平差异 633 | * @param error 小程序api返回的错误对象 634 | * @param reject 上层的promise reject 函数 635 | * @param config 636 | */ 637 | function transformError(error, reject, config) { 638 | switch (platFormName) { 639 | case "wechat" /* 微信 */: 640 | if (error.errMsg.indexOf('request:fail abort') !== -1) { 641 | // Handle request cancellation (as opposed to a manual cancellation) 642 | reject(createError('Request aborted', config, 'ECONNABORTED', '')); 643 | } 644 | else if (error.errMsg.indexOf('timeout') !== -1) { 645 | // timeout 646 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '')); 647 | } 648 | else { 649 | // NetWordError 650 | reject(createError('Network Error', config, null, '')); 651 | } 652 | break; 653 | case "dd" /* 钉钉 */: 654 | case "alipay" /* 支付宝 */: 655 | // https://docs.alipay.com/mini/api/network 656 | if ([14, 19].includes(error.error)) { 657 | reject(createError('Request aborted', config, 'ECONNABORTED', '', error)); 658 | } 659 | else if ([13].includes(error.error)) { 660 | // timeout 661 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error)); 662 | } 663 | else { 664 | // NetWordError 665 | reject(createError('Network Error', config, null, '', error)); 666 | } 667 | break; 668 | case "baidu" /* 百度 */: 669 | // TODO error.errCode 670 | reject(createError('Network Error', config, null, '')); 671 | break; 672 | } 673 | } 674 | /** 675 | * 将axios的请求配置,转换成各个平台都支持的请求config 676 | * @param config 677 | */ 678 | function transformConfig(config) { 679 | var _a; 680 | if (["alipay" /* 支付宝 */, "dd" /* 钉钉 */].includes(platFormName)) { 681 | config.headers = config.header; 682 | delete config.header; 683 | if ("dd" /* 钉钉 */ === platFormName && config.method !== 'GET' && ((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') { 684 | // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化 685 | config.data = JSON.stringify(config.data); 686 | } 687 | } 688 | return config; 689 | } 690 | 691 | var isJSONstr = function (str) { 692 | try { 693 | return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]'; 694 | } 695 | catch (error) { 696 | return false; 697 | } 698 | }; 699 | function mpAdapter(config, _a) { 700 | var _b = (_a === void 0 ? {} : _a).transformRequestOption, transformRequestOption = _b === void 0 ? function (requestOption) { return requestOption; } : _b; 701 | var request = getRequest(); 702 | return new Promise(function (resolve, reject) { 703 | var requestTask; 704 | var requestData = config.data; 705 | var requestHeaders = config.headers; 706 | // baidu miniprogram only support upperCase 707 | var requestMethod = (config.method && config.method.toUpperCase()) || 'GET'; 708 | // miniprogram network request config 709 | var mpRequestOption = { 710 | method: requestMethod, 711 | url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer), 712 | timeout: config.timeout, 713 | // Listen for success 714 | success: function (mpResponse) { 715 | var response = transformResponse(mpResponse, config, mpRequestOption); 716 | settle(resolve, reject, response); 717 | }, 718 | // Handle request Exception 719 | fail: function (error) { 720 | transformError(error, reject, config); 721 | }, 722 | complete: function () { 723 | requestTask = undefined; 724 | } 725 | }; 726 | // HTTP basic authentication 727 | if (config.auth) { 728 | var _a = [config.auth.username || '', config.auth.password || ''], username = _a[0], password = _a[1]; 729 | requestHeaders.Authorization = 'Basic ' + encoder(username + ':' + password); 730 | } 731 | // Add headers to the request 732 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 733 | var _header = key.toLowerCase(); 734 | if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') { 735 | // Remove Content-Type if data is undefined 736 | // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer' 737 | delete requestHeaders[key]; 738 | } 739 | }); 740 | mpRequestOption.header = requestHeaders; 741 | // Add responseType to request if needed 742 | if (config.responseType) { 743 | mpRequestOption.responseType = config.responseType; 744 | } 745 | if (config.cancelToken) { 746 | // Handle cancellation 747 | config.cancelToken.promise.then(function onCanceled(cancel) { 748 | if (!requestTask) { 749 | return; 750 | } 751 | requestTask.abort(); 752 | reject(cancel); 753 | // Clean up request 754 | requestTask = undefined; 755 | }); 756 | } 757 | // Converting JSON strings to objects is handed over to the MiniPrograme 758 | if (isJSONstr(requestData)) { 759 | requestData = JSON.parse(requestData); 760 | } 761 | if (requestData !== undefined) { 762 | mpRequestOption.data = requestData; 763 | } 764 | requestTask = request(transformRequestOption(transformConfig(mpRequestOption))); 765 | }); 766 | } 767 | 768 | module.exports = mpAdapter; 769 | module.exports.default = mpAdapter; --------------------------------------------------------------------------------