{"id":22879313,"url":"https://github.com/anthinkingcoder/zy-fetch","last_synced_at":"2025-05-07T00:30:17.363Z","repository":{"id":57406914,"uuid":"143441925","full_name":"anthinkingcoder/zy-fetch","owner":"anthinkingcoder","description":"fetch api based http client for the brower \u0026 node.js,support Interceptors,timeout,retry","archived":false,"fork":false,"pushed_at":"2019-05-01T08:20:19.000Z","size":825,"stargazers_count":7,"open_issues_count":1,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-26T06:26:55.151Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/anthinkingcoder.png","metadata":{"files":{"readme":"README.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}},"created_at":"2018-08-03T15:09:44.000Z","updated_at":"2020-12-31T06:43:33.000Z","dependencies_parsed_at":"2022-09-19T07:12:54.761Z","dependency_job_id":null,"html_url":"https://github.com/anthinkingcoder/zy-fetch","commit_stats":null,"previous_names":[],"tags_count":61,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anthinkingcoder%2Fzy-fetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anthinkingcoder%2Fzy-fetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anthinkingcoder%2Fzy-fetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anthinkingcoder%2Fzy-fetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/anthinkingcoder","download_url":"https://codeload.github.com/anthinkingcoder/zy-fetch/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252790897,"owners_count":21804675,"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":[],"created_at":"2024-12-13T16:38:51.300Z","updated_at":"2025-05-07T00:30:17.302Z","avatar_url":"https://github.com/anthinkingcoder.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# zy-fetch\nfetch api base http client for the brower \u0026 node,support Interceptors\n\n\n\n## Features\n\n- Use [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser when not support fetch,see [Fetch-polyfill](https://github.com/github/fetch)\n- Use [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) from the browser when support fetch\n- Use [node-fetch](https://github.com/bitinn/node-fetch) from the node.js\n- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API\n- Supports automatic transformResponse,transformRequest\n- Supports automatic build SearchParams\n- Support Timeout\n- Support Retry Fetch\n- Support Interceptors\n- Support Create Instance\n\n## Browser Support\n\n- Chrome\n- Firefox\n- Safari 6.1+\n- Internet Explorer 9+\n\n\n## Installing\n\nUsing npm:\n\n```bash\n$ npm install zy-fetch -s\n```\nand\n```javascript\n//global use \n// it will do that -\u003e self.fetch = zyFetch or global.fetch = zyFetch\nimport 'zy-fetch'\n\n//module use\nimport zyFetch from 'zy-fetch/lib/zyFetchs'\n```\n\nUsing cdn:\n\n```html\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/zy-fetch@1.7.1/dist/zy-fetch.min.js\"\u003e\u003c/script\u003e\n```\n\n## api\n### Request method aliases\n##### fetch(init,option)\n##### fetch.send(init,option)\n##### fetch.get(init[, option])\n##### fetch.delete(init[, option])\n##### fetch.head(init[, option])\n##### fetch.options(init[, option])\n##### fetch.post(init[, body[, option]])\n##### fetch.put(init[, body[, option]])\n##### fetch.patch(init[, body[, option]])\n\n### Concurrency\n##### fetch.all(fetchArray)\n##### fetch.allByOrder(fetchArray)\n##### fetch.spread(callback)\n\n### Creating an instance\nYou can create a new instance of zyFetch with a custom config.\n##### fetch.create([config])\n\n### nativeFetch\n##### fetch.nativeFetch (get window.fetch or node-fetch)\n\n## request config\nfetch(init,option),in addition to fetch's own option, zy-fetch include other option,like this\n```js\n      responseType: 'json', //json,blob,formData,arrayBuffer,text\n      transformResponse: false, //default false,true represents automatic  transform response \n      timeout: 1000, //to set request timeout time \n      baseUrl: ''  //base url\n      retry: Number //retry count\n      retryTimeout: 1000 //retry timeout\n```\n\n## Global Config\n### defaults\n```js\n    const config = {\n      headers: {},\n      responseType: 'json', //json,blob,formData,arrayBuffer,text\n      method: 'get',\n      transformResponse: false, //default false,true represents automatic  transform response \n      transformRequest: false, //default false,true represents automatic  transform request\n      credentials: 'same-origin', //omit,include,same-origin\n      timeout: 0,\n      baseUrl: '' // base url,\n    }\n```\n### Set Config\nyou also can set golbal config like this\n```js\n     fetch.config.headers['Content-Type'] = 'application/json'\n     fetch.config.responseType = 'blob'\n     fetch.config.transformResponse = true\n       fetch.config.transformRequest = true\n     fetch.config.timeout = 3000\n     fetch.config.baseUrl = 'https://www.zzz.com'\n\n```\n\n## Example\n\n### NORMAL\n\u003e This is the writing of fetch API, see [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n```js\nfetch('/users.html', {\n  headers: {\n    \n  }\n})\n  .then(function(response) {\n    return response.text()\n  }).then(function(body) {\n    document.body.innerHTML = body\n  })\n```\n\n### MORE\n\u003e This is the writing of zy-fetch API\n#### GET\n```js\n// to get userinfo\nimport 'zy-fetch'\nfetch.get('/mock/userinfo?userid=123')\n  .then(function (response) {\n    return response.json()\n  })\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n\n// or\nfetch.get('/mock/userinfo', {\n  params: {\n    userid:123\n  }\n})\n  .then(function (response) {\n    return response.json()\n  })\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n\n```\n#### POST\n\n```js\n// to add user\nimport 'zy-fetch'\nfetch.post('/user/add', JSON.stringify({'name':'zhoulin'}))\n  .then(function (response) {\n    return response.json()\n  })\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n\n```\n#### Concurrent Requests\n```js\n  import 'zy-fetch'\n  const userFetch = fetch('api1')\n  const teacherFetch = fetch('api2')\n  fetch.all([userFetch,teacherFetch])\n  .then((responses) =\u003e {\n    return fetch.all(responses[0].json(),responses[1].text())\n  }).then(datas =\u003e {\n    console.info(['user',datas[0]])\n     console.info(['teacher',datas[1]])\n  })\n  \n  // use fetch.spread to simplify\n   fetch.all(userFetch,teacherFetch)\n   .then(fetch.spread(function(userRes,teacherRes) {\n     return fetch.all(userRes.json(),teacherRes.text())\n   })).then(fetch.spread(function(user,teacher) {\n     //...\n   }))\n```\n\n#### Execute fetch in sequence\n```js\n import 'zy-fetch'\n const fetch1 = fetch.bind(fetch, './mock/a.json')\n    const fetch2 = fetch.bind(fetch, './mock/a.json')\n  fetch.allByOrder([fetch1, fetch2]).then(fetch.spread((response1, response2) =\u003e {\n    console.info([response1, response2])\n  }))\n```\n\n## transformRequest\nyou can set transformRequest  to auto transformRequest, like this\n```js\nimport 'zy-fetch'\nfetch.post('/add/user', {\n  name: 'zhoulin'\n}, {\n  transformRequest:true\n})\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n\n//equal\nfetch.post('/add/user',JSON.stringify({\n   name: 'zhoulin'\n  }))\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n```\n\n## transformResponse\nyou can set responseType and transformResponse to auto transformResponse, like this\n```js\nimport 'zy-fetch'\nfetch.get('/mock/city.json', {\n  transformResponse:true, //default false\n  responseType: 'json' //default json\n})\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n```\n\n## Timeout\n```js\n fetch('./mock/a.json', {\n     transformResponse: true,\n     timeout:1000,\n   }).then(function (res) {\n     console.info(res)\n   }).catch(function (err) {\n     console.info(err) //new Error('request timeout')\n   })\n\n```\n\n## Retry Fetch\n```js\n fetch('./mock/a.json', {\n     transformResponse: true,\n     retry:3,\n     retryTimeout:1000,\n   }).then(function (res) {\n     console.info(res)\n   }).catch(function (err) {\n     console.info(err)\n   })\n```\n\n\n## Interceptors\n\nYou can intercept requests or responses,add a request interceptor before request send or  add a response interceptor after response finished.\nresponse interceptor include transform interceptor and noTransform interceptor \n```zy-fetch``` inside is a mode of ```responsibility chain```\n\n1.if not automatic transform response\n\u003eThis order is -\u003erequest interceptors -\u003e fetch -\u003e checkstatus -\u003e noTransform interceptor\n\n2.if automatic transform response\n\u003eThis order is -\u003erequest interceptors -\u003e fetch -\u003e checkstatus -\u003e noTransform interceptor -\u003e transformResponse -\u003e transform interceptor\n\n### example\n```js\n// Add a x-csrf-token header\nfetch.interceptors.request.use(\n  request =\u003e {\n    const csrfToken = cookies.get('csrfToken')\n    if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(request.method)) {\n      request.headers.append('x-csrf-token',csrfToken)\n    }\n    // remember return\n    return request\n  },\n  error =\u003e {\n    return Promise.reject(error)\n  }\n)\n\n// Add a common response interceptor, to handle not login\nfetch.interceptors.response.noTransform.use(\n  response =\u003e {\n    return response.json(function (data) {\n      return data\n    })\n  },\n  error =\u003e {\n    return Promise.reject('system error')\n  })\n  \n fetch.interceptors.response.transform.use(\n   data =\u003e {\n       if (data.data.code === '0006') {\n             // handle not login\n             }\n             //remember return\n             return response\n   },\n   error =\u003e {\n     return Promise.reject('system error')\n   })\n ```\n## Create Instance\n```js\n//fetch.create(config)\nconst instance = fetch.create({\n  transformResponse:true\n})\ninstance.get('/mock/city.json', {\n})\n  .then(function (data) {\n    console.info(data)\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n```\n\n## checkStatus\nA fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example.  An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true,\nso we Built in  ```checkStatus``` function\n```js\nfunction checkStatus () {\n  if (response.status \u003e= 200 \u0026\u0026 response.status \u003c 300) {\n      return response\n    } else {\n      let error = new Error(response.statusText)\n      error.response = response\n      throw error\n    }\n}\n```\n\n## Aborting Fetch\n  browsers \u0026 node that do not support fetch will also not support AbortController or AbortSignal , see [polyfill](https://github.com/mo/abortcontroller-polyfill),\n```js\n  import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'\n  import 'zy-fetch'\n  var controller = new AbortController();\n  var signal = controller.signal;\n  fetch('/city.json', {'signal':signal}).then(function (result) {\n    console.info(result)\n  }).catch(function (error) {\n    console.info(error)\n  })\n  setTimeout(function () {\n    controller.abort()\n  })\n\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanthinkingcoder%2Fzy-fetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanthinkingcoder%2Fzy-fetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanthinkingcoder%2Fzy-fetch/lists"}