{"id":22541356,"url":"https://github.com/pandaoh/js-xhttp","last_synced_at":"2025-04-09T21:45:52.210Z","repository":{"id":38401399,"uuid":"448791187","full_name":"pandaoh/js-xhttp","owner":"pandaoh","description":"An HTTP tool is based on Axios that can make ajax more convenient and universal, easier to manage, and more efficient and unified. XHttp 是一个基于 axios 二次封装的 HTTP 请求工具，可以让你在项目中使用 http 请求时更加简单，更加通用灵活，更加高效统一，且易于全局管理。","archived":false,"fork":false,"pushed_at":"2024-01-24T02:15:50.000Z","size":1440,"stargazers_count":4,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-04-24T08:07:40.432Z","etag":null,"topics":["ajax","axios","http","javascript","js-http","js-xhttp","request","rollup","typescript","x-xrequest","xhttp","xrequest"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/js-xhttp","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pandaoh.png","metadata":{"files":{"readme":"README.en.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-17T07:19:09.000Z","updated_at":"2024-06-21T20:49:30.227Z","dependencies_parsed_at":"2024-01-24T03:28:42.568Z","dependency_job_id":"757e88cb-74da-4b32-86bf-98e898134600","html_url":"https://github.com/pandaoh/js-xhttp","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/pandaoh%2Fjs-xhttp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pandaoh%2Fjs-xhttp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pandaoh%2Fjs-xhttp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pandaoh%2Fjs-xhttp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pandaoh","download_url":"https://codeload.github.com/pandaoh/js-xhttp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248119439,"owners_count":21050754,"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","axios","http","javascript","js-http","js-xhttp","request","rollup","typescript","x-xrequest","xhttp","xrequest"],"created_at":"2024-12-07T12:15:32.940Z","updated_at":"2025-04-09T21:45:52.171Z","avatar_url":"https://github.com/pandaoh.png","language":"JavaScript","readme":"[中文 README](https://github.com/pandaoh/js-xhttp)\n\n# XHttp\n\n## 介绍\n\n\u003e An HTTP tool is based on Axios that can make ajax more convenient and universal, easier to manage, and more efficient and unified.\n\n-----\n\n### Features\n\n* Compatible with `axios`.\n* Basic request encapsulation.\n* Request, response, error interception and handling.\n* Request header interception processing.\n* Log output, callback (whether successful or not) Hooks when the request is completed.\n* Actively cancel requests, cancel duplicate requests, and add request whitelist.\n* Request result processing, permission control, and so on.\n* Request to retry `axios-retry`.\n* Default error handling, which can also be customized.\n* Provide a method for modifying the default configuration of an instance.\n* Provide common request-related method tool class `XHttpUtils`. (Singleton Class-no initialization required-`1.4.0` and above cancel-transfer to [js-xxx JavaScript Function Library](https://www.npmjs.com/package/js-xxx))\n\n## Install\n\n```shell\nnpm install js-xhttp -S\n```\n\n## Import/Require\n\n```javascript\nconst { XHttp, XHttpMethod, XHttpUtils, Axios, CODE_MSG } = require('js-xhttp');\nimport { XHttp, XHttpMethod, XHttpUtils, Axios, CODE_MSG } from 'js-xhttp';\nimport XHttp from 'js-xhttp';\n```\n\n## Use\n\n### Initialize an instance\n\n```javascript\nimport XHttp from \"js-xhttp\";\nimport { message, notification } from \"@/plugins/antd\";\n\n// globally initialize an instance. All configurations are as follows, all optional parameters. You can also XHttp.create(); initialize directly.\nconst $http = XHttp.create(\n  {\n    timeout: 10000, // timeout default: 30000\n    cancelDuplicatedRequest: true, // Whether to cancel the duplicate request default: true\n    rejectErrorPromise: false, // [default: true] Use with errorHandler to reject the requestError\n    retryConfig: {\n      // Retry the configuration\n      retry: 3, // retry count\n      delay: 1000, // Base delay time for each retry\n    },\n    // Use formatResultAdaptor handle response data or use request config.formatResultAdaptor handle response data\n    requestHandler: (config: any) =\u003e {\n      console.log(\"requestHandler\", config); // Intercept processing before request\n      console.log(config?.cancelRequest); // Cancel request\n    },\n    responseHandler: (response: any) =\u003e {\n      // Response handler before response\n      if (response.data.code != 0) {\n        message.error(response.data.msg);\n      }\n      console.log(response.config);\n    },\n    errorHandler: (error: any, requestConfig: any) =\u003e {\n       console.log(requestConfig);\n      // Error handler before error\n      if (!XHttp.isCancel(error) \u0026\u0026 !error.message?.includes(\"custom-error\")) {\n        notification.error({\n          message: `${error.status}-${error.statusText}`,\n          description: `发生错误了 ${error.data?.msg ?? error?.data?.message ?? \"未知错误\"}`,\n        });\n      }\n      // Whether to pass the error to the outer layer. If not, you can avoid customizing the error handling for each request.\n      // return Promise.reject(error); \n      console.log(\"errorHandler\", error); // Error log\n      if (requestConfig.rejectErrorPromise) {\n        return Promise.reject(error);\n      }\n    },\n    setRequestHeaders: (config: any) =\u003e {\n      // Set request headers here, you can also use $http.setAuthToken to set the authorization token.\n      return config; // Returns the configuration object, and the request header can be modified. must return an Headers object, otherwise an error will be thrown.\n    },\n    requestFinally: (requestConfig: any) =\u003e {\n      console.log(\"requestFinally Hooks\", requestConfig); // The callback when the request is completed, regardless of the result.\n    },\n  },\n  // axios configuration\n  {\n    baseURL: import.meta.env.VITE_REQUEST_BASE_URL, // Set the base url by environment variables\n    validateStatus: (status: number) =\u003e {\n      // XHttp default status validation rule is all return true.\n      // You can customize the status validation rule here.\n      // Return true means success(resolve), otherwise failure(reject). You can customize the status validation rule here.\n      return status \u003e= 200 \u0026\u0026 status \u003c 300;\n    },\n  }\n);\n\nexport default $http;\n// You can also use the following methods: get post put patch delete request. You can also use the axios object, tools class, etc.\n```\n\n### Basic request\n\n```javascript\nXHttp.get('/tests', { start: 0, count: 20 }, {});\nXHttp\n  .post(\n  '/login',\n  { username: 'test', password: '123456' },\n  { headers: { 'Content-Type': 'application/json' }}\n  ).then((res) =\u003e {\n    console.log('res', res);\n  })\n  .catch((err) =\u003e {\n    console.log('err', err);\n  })\n  .finally(() =\u003e {\n    console.log('finally TEST');\n  });\nXHttp.get('/test', { start: 0, count: 20 }, {}, true); \n// The whitelist cannot be cancelled unless cancelWhiteListRequest() is called\nXHttp.request(XHttpMethod.GET, '/tests', { params: { start: 0, count: 20 }, rejectErrorPromise: true }, {}, true);\n\n$http.get('/tests', { start: 0, count: 20 }, {});\n$http\n  .post(\n  '/login',\n  { username: 'test', password: '123456' },\n  { headers: { 'Content-Type': 'application/json' }, rejectErrorPromise: true }\n  ).then((res) =\u003e {\n    console.log('res', res);\n  })\n  .catch((err) =\u003e {\n    console.log('err', err);\n  })\n  .finally(() =\u003e {\n    console.log('finally TEST');\n  });\n$http.get('/test', { start: 0, count: 20 }, {}, true); \n// The whitelist cannot be cancelled unless cancelWhiteListRequest() is called\n$http.request(XHttpMethod.GET, '/tests', { params: { start: 0, count: 20 } }, {}, true);\n```\n\n### XHttp methods\n\n```javascript\n$http.setAuthToken('test token');\n$http.setBaseURL('http://localhost:666');\nconsole.log($http.getInstance().defaults.headers);\n$http.cancelRequest('all');\n$http.cancelWhiteListRequest('all white list');\n\nXHttp.setAuthToken('test token');\nXHttp.setBaseURL('http://localhost:666');\nconsole.log(XHttp.getInstance().defaults.headers);\nXHttp.cancelRequest('all');\nXHttp.cancelWhiteListRequest('all white list');\n/* ...and so more... */\n```\n\n### XHttpUtils methods\n\n```javascript\nXHttpUtils.typeof({}); // 'object'\n/* ...and so more... */\n```\n\n### XHttpMethod\n\n```javascript\nconsole.log(XHttpMethod);\n// {\n//   GET: 'GET',\n//   POST: 'POST',\n//   PUT: 'PUT',\n//   DELETE: 'DELETE',\n//   PATCH: 'PATCH',\n//   OPTIONS: 'OPTIONS'\n// }\n```\n\n### Axios\n\n```javascript\nAxios.get('/axios')\n  .then(function (response) {\n    console.log(response.data);\n    console.log(response.status);\n    console.log(response.statusText);\n    console.log(response.headers);\n    console.log(response.config);\n  })\n  .catch((e) =\u003e {});\n/* ...and so more... */\n```\n\n* [Axios Docs](https://www.axios-http.cn/docs/intro)\n* [Axios Github](https://github.com/axios/axios)\n\n## API List\n\n[API Docs](https://github.com/pandaoh/js-xhttp/blob/master/docs/README.md)\n\n## Others\n\n* XHttp is based on [axios](https://github.com/axios/axios) secondary encapsulation implementation.\n* For problem feedback, you can create [Issue](https://github.com/pandaoh/js-xhttp/issues) or submit [Pull Request](https://github.com/pandaoh/js-xhttp/pulls), email: [hxbpandaoh@163.com](mailto:hxbpandaoh@163.com).\n* [Blog](http://a.biugle.cn)\n* Leo He\n* More functions are being improved...\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpandaoh%2Fjs-xhttp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpandaoh%2Fjs-xhttp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpandaoh%2Fjs-xhttp/lists"}