{"id":20980563,"url":"https://github.com/wocanbe/luck7-ajax","last_synced_at":"2025-03-13T10:17:18.188Z","repository":{"id":57290840,"uuid":"153744411","full_name":"wocanbe/luck7-ajax","owner":"wocanbe","description":null,"archived":false,"fork":false,"pushed_at":"2021-08-11T03:06:38.000Z","size":17,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-08T06:11:45.943Z","etag":null,"topics":["ajax","manage","project"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wocanbe.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-19T07:37:15.000Z","updated_at":"2021-08-11T03:06:40.000Z","dependencies_parsed_at":"2022-09-01T15:14:20.270Z","dependency_job_id":null,"html_url":"https://github.com/wocanbe/luck7-ajax","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wocanbe%2Fluck7-ajax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wocanbe%2Fluck7-ajax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wocanbe%2Fluck7-ajax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wocanbe%2Fluck7-ajax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wocanbe","download_url":"https://codeload.github.com/wocanbe/luck7-ajax/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243130950,"owners_count":20241177,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajax","manage","project"],"created_at":"2024-11-19T05:29:08.289Z","updated_at":"2025-03-13T10:17:18.159Z","avatar_url":"https://github.com/wocanbe.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# luck7-ajax\n\n可以拥有统一配置的项目层面的对ajax的再封装，使用简洁，可以同时存在多个\n\n```javascript\n// 创建ajax对象\nconst ajax = new Ajax(apiLists, commonConfigs, ajaxConfigs, apiMethods)\n// 使用ajax对象发起请求\najax.do(apiName, params) // 没有请求参数的时候，params可以不写\n  .then(res =\u003e {\n    console.log(res)\n  }).catch(err =\u003e {\n    console.error(err)\n  })\n```\n\n## 参数\n\n * apiLists\n\n  Array类型，api接口列表，格式为```key: {method, url, options}```，支持简写\n\n * commonConfigs\n\n  Object类型，对ajax请求的配置(如headers、timeout等)，来自axios框架，参考``请求配置项``，默认值如下\n  ```javascript\n  {\n    method: 'POST',\n    parseJson: true\n  }\n  ```\n\n * ajaxConfigs\n\n  Object类型，框架专有的配置，用于对请求/返回数据进行处理，支持如下四个参数\n  ```javascript\n  {\n    // publicParams: Function, // 公共参数，已移除，建议通过instance的拦截实现\n    lang: Object, // 错误提示文本\n    isStrict: true // 是否开启严格模式\n  }\n  ```\n\n  错误提示文本默认值\n  ```javascript\n  {\n    noList: '配置错误: 缺少接口配置(list)',\n    methodError: '配置错误: #apiName#请求类型异常#method#',\n    urlError: '配置错误: #apiName#缺少请求地址(url)',\n    typeError: '使用错误: 接口参数类型错误',\n    noConfig: '使用错误: 接口#apiName#未配置',\n    netError: '服务器错误: 状态码：#status#'\n  }\n  ```\n * apiMethods\n\n 跟``apiLists``中的key对应，代表相应的api请求后的处理方法，格式如下\n\n \n  ```javascript\n  {\n    key () { // key的唯一特例是'_',代表通用处理方法,将对所有未配置method的api生效\n      return {\n        request (req) {return {}}, // 对request参数进行处理，返回处理后的请求参数\n        response (res) {return {}}, // 对返回数据进行处理，返回处理后的数据(也可以在这儿交由vuex处理，返回空对象)\n        error (err) {} // 对异常进行处理\n      }\n    }\n  }\n  ```\n## 请求配置项\n\n支持所有axios支持的配置，详情参考[axios](https://github.com/mzabriskie/axios) 的\"Request Config\"\n\n - 请求配置项支持**实例级配置**和**单次请求配置**\n\n## 项目使用实例\n\n```javascript\n// src/config/ajax\nimport store from '@/store'\nconst list = {\n  demo1: {\n    url: '/mock1'\n  },\n  // 可以简写为 demo1: '/mock1'\n  // 使用请求超时\n  demo2: {\n    method: 'GET', // 默认值为POST\n    url: '/mock2', // 请求地址，必填且不能为空\n    data: {}, // 请求参数，可以进行一些特殊写法，如写成'vuex.xxxx'，然后在methods中处理成对应的vuex数据\n    options: { // 请求配置项\n      timeout: 1000 // 请求超时时间\n    }\n  },\n  // 使用URL参数（:path）\n  demo3: '/:id/mock3',\n  login: '/login',\n}\nconst baseURL = '/mock'\nconst commonConfigs = { // ajax配置，详见axios、flyio，默认使用flyio\n  // method: 'POST', // 框架默认值\n  // interceptors: fun // 详见axios/flyip的interceptors说明\n  baseURL\n}\nconst ajaxConfigs = {\n  // lang\n}\nconst methods = {\n  _ () {\n  // _代表对所有的过滤，用于实现对request和respone的拦截\n  // _跟其他的method配置(如login)不能同时生效\n  // 为什么是function？为了实现一些情况下request和response共用变量，并且每次请求该变量都会变化的情况，如对数据进行加解密的情况\n    return {\n      request (req) {\n        const token = sessionStorage.getItem('token')\n        req[0].options['headers'] = {'Access-token': token}\n        const data = req[1]\n        const userid = sessionStorage.getItem('userid')\n        const backData = {userid}\n        for (const k in data) {\n          let v = data[k]\n          if (typeof v === 'string' \u0026\u0026 v.substr(0, 5) === 'vuex.') { // 处理vuex数据\n            const path = v.substr(5).split('.')\n            v = path.reduce((acc, cur) =\u003e acc[cur], store.state)\n          }\n          backData[k] = v\n        }\n        req[1] = backData\n        return req\n      },\n      response (res) {\n        if (res.code !== 0) {\n          throw new Error(res.msg)\n        } else return res.data\n      }\n    }\n  },\n  login () {\n    return {\n      response (res) {\n        store.commit('login/LOGIN_DATA', res)\n      },\n      error (err) {\n        store.commit('ERR_MSG', '登录失败，错误详情：' + err.message)\n      }\n    }\n  }\n}\nexport {list, commonConfigs, ajaxConfigs, methods}\n\n// src/utils/ajax.js\nimport isFunction from 'lodash/isFunction'\nimport Ajax from 'luck7-ajax'\nimport {list, commonConfigs, ajaxConfigs} from '../config/ajax'\n\nconst _ajax = new Ajax(list, commonConfigs, ajaxConfigs, methods)\n\nconst ajax = function (apiName, params) {\n  return _ajax.do(apiName, params)\n}\nexport default ajax\n\n// main.js\najax('demo1', {\n  pageNo: 1,\n  size: 10\n}).then((data) =\u003e {\n  console.log(data)\n}).catch((e) =\u003e {\n  console.error(e.message)\n})\n\najax(['demo2', 'demo3'], []) // 第二个数组不能省略\n  .then((datas) =\u003e {\n    console.log(datas[0], datas[1])\n  }).catch((err) =\u003e {\n    console.error(err.message)\n  })\n/*\n上例等价于\nPromise.all([\n  ajax('demo2'),\n  ajax('demo3')\n]).then((datas) =\u003e {\n  console.log(datas[0], datas[1])\n}).catch((err) =\u003e {\n  console.error(err.message)\n})\n*/\n\najax(\n  '/login', // 注意：这种使用方式在严格模式下会报错，只能在非严格模式下使用\n  {\n    username: 'admin',\n    password: 'admin'\n  }\n).then((data) =\u003e {\n  console.log(data)\n}).catch((e) =\u003e {\n  console.error(e.message)\n})\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwocanbe%2Fluck7-ajax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwocanbe%2Fluck7-ajax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwocanbe%2Fluck7-ajax/lists"}