{"id":15893908,"url":"https://github.com/chinanf-boy/explain-unfetch","last_synced_at":"2026-01-15T23:54:57.350Z","repository":{"id":90548259,"uuid":"118137413","full_name":"chinanf-boy/explain-unfetch","owner":"chinanf-boy","description":"explain: unfetch {Bare minimum fetch polyfill in 500 bytes. }🆒 微小fetch","archived":false,"fork":false,"pushed_at":"2018-01-19T14:48:52.000Z","size":4,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-08T08:47:14.446Z","etag":null,"topics":["explain","fetch","unfetch"],"latest_commit_sha":null,"homepage":"","language":null,"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/chinanf-boy.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-01-19T14:48:36.000Z","updated_at":"2018-01-19T14:57:01.000Z","dependencies_parsed_at":"2023-07-18T11:00:18.022Z","dependency_job_id":null,"html_url":"https://github.com/chinanf-boy/explain-unfetch","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/chinanf-boy%2Fexplain-unfetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chinanf-boy%2Fexplain-unfetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chinanf-boy%2Fexplain-unfetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chinanf-boy%2Fexplain-unfetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chinanf-boy","download_url":"https://codeload.github.com/chinanf-boy/explain-unfetch/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246866100,"owners_count":20846496,"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":["explain","fetch","unfetch"],"created_at":"2024-10-06T08:14:03.292Z","updated_at":"2026-01-15T23:54:57.323Z","avatar_url":"https://github.com/chinanf-boy.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# unfetch\n\n\u003e 超小的 `fetch` polyfill in 500 字节. \n\n[![explain](http://llever.com/explain.svg)](https://github.com/chinanf-boy/Source-Explain)\n    \nExplanation\n\n\u003e \"version\": \"3.0.0\"\n\n[github source](https://github.com/developit/unfetch)\n\n~~[english](./README.en.md)~~\n\n---\n\n好了，这么小，只有一个主文件\n\n[src/index.js](./unfetch/src/index.js)\n\n不如先看看例子\n\n[jsfiddle-unfetch-例子](https://jsfiddle.net/developit/qrh7tLc0/)\n---\n\n- `ponyfill vs polyfill`\n\n- [index-XMLHttpRequest的设置](#index)\n\n- [response-数据的处理](#response)\n\n- ~~[npm-run-关于这个项目的配置与构建](./npm-run.readme.md)~~\n---\n\n## ponyfill vs polyfill\n\n作为 [ponyfill](https://ponyfill.com/): 只使用`unfetch`\n\n``` js\nimport fetch from 'unfetch';\n\nfetch('/foo.json')\n  .then( r =\u003e r.json() )\n  .then( data =\u003e {\n    console.log(data);\n  });\n\n```\n\n全局, 作为 [polyfill](https://ponyfill.com/#polyfill): 如果有原生，用原生，没有则用`unfetch`\n\n``` js\nimport 'unfetch/polyfill';\n\n// \"fetch\" 已经加载了，如果不存在的话\n\nfetch('/foo.json')\n  .then( r =\u003e r.json() )\n  .then( data =\u003e {\n    console.log(data);\n  });\n```\n\n\u003e `要`，还是`不要`《-🌟-》原生api，这是一个问题\n\n---\n\n例子-jsfiddle\n\n``` js\nunfetch('//jsonplaceholder.typicode.com/posts', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json' },\n\tbody: JSON.stringify({\n\t\ttitle: 'foo',\n\t\tbody: 'bar',\n\t\tuserId: 1\n\t})\n})\n\t.then( r =\u003e r.json() )\n\t.then( data =\u003e {\n\t\tlog(data);\n\t\t\n\t\tunfetch('//jsonplaceholder.typicode.com/posts/1')\n\t\t\t.then( r =\u003e r.json() )\n\t\t\t.then( log )\n\t});\n```\n\n## index\n\n``` js\nexport default typeof fetch=='function' ? fetch.bind()      // fetch.bind() ,使用原生\n    : function(url, options) {\n        \n\toptions = options || {};\n\treturn new Promise( (resolve, reject) =\u003e { // 增加 Promise --\u003e async/await\n\t\tlet request = new XMLHttpRequest();\n\n\t\trequest.open(options.method || 'get', url, true);\n\n\t\tfor (let i in options.headers) {\n            // headers: { 'Content-Type': 'application/json' },\n\t\t\trequest.setRequestHeader(i, options.headers[i]); // 设置请求-头 ---- 1\n\t\t}\n\n\t\trequest.withCredentials = options.credentials=='include'; // ----- 2\n\n\t\trequest.onload = () =\u003e { //        --- 3\n\t\t\tresolve(response()); // 获取-函数触发\n\t\t};\n\n\t\trequest.onerror = reject; //   --- 4\n\n        request.send(options.body);  // --- 5\n    //     \tbody: JSON.stringify({\n        // \ttitle: 'foo',\n        // \tbody: 'bar',\n        // \tuserId: 1\n        // })\n\n//  ---- 获取数据后，函数运行\n\t\tfunction response() {\n            // ... \n        }\n\t});\n}\n\n```\n\n1. `request.setRequestHeader`\n\n\u003e 给指定的HTTP请求头赋值.\n\n2. `request.withCredentials`\n\n\u003e 表明在进行跨站(cross-site)的访问控制(Access-Control)请求时，是否使用认证信息(例如cookie或授权的header)。 默认为 false。\n\n3. `request.onload`\n\n\u003e 当一个资源及其依赖资源已完成加载时，将触发load事件。[mdn文档](https://developer.mozilla.org/zh-CN/docs/Web/Events/load)\n\n4. `request.onerror`\n\n\u003e 当一个资源加载失败时会触发error事件。[mdn文档](https://developer.mozilla.org/zh-CN/docs/Web/Events/error)\n\n5. `request.send`\n\n\u003e 发送请求. 如果该请求是异步模式(默认),该方法会立刻返回. 相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.\n\n[有关-XMLHttpRequest-更多](https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest)\n\n---\n\n## response\n\n``` js\n\t\trequest.onload = () =\u003e { //        --- 3\n\t\t\tresolve(response()); // 获取-函数触发\n\t\t};\n\n```\n\n数据获取后，`response` 触发\n\n``` js\nfunction response() {\n    let keys = [],\n        all = [],\n        headers = {},\n        header;\n\n    request.getAllResponseHeaders().replace(/^(.*?):\\s*?([\\s\\S]*?)$/gm, (m, key, value) =\u003e {\n        keys.push(key = key.toLowerCase()); // 所有 key\n        all.push([key, value]); // \n        header = headers[key];\n        headers[key] = header ? `${header},${value}` : value;\n    });\n\n    return {\n        ok: (request.status/100|0) == 2,\t\t// 200-299\n        status: request.status,\n        statusText: request.statusText,\n        url: request.responseURL,\n        clone: response,\n        text: () =\u003e Promise.resolve(request.responseText),\n        json: () =\u003e Promise.resolve(request.responseText).then(JSON.parse),\n        blob: () =\u003e Promise.resolve(new Blob([request.response])),\n        headers: {\n            keys: () =\u003e keys,\n            entries: () =\u003e all,\n            get: n =\u003e headers[n.toLowerCase()],\n            has: n =\u003e n.toLowerCase() in headers\n        }\n    };\n}\n```\n\n- `getAllResponseHeaders`\n\n\u003e 返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回null. \n\n\u003e 注意: For multipart requests, this returns the headers from the current part of the request, not from the original channel.\n---\n\n\u003e 返回的对象-解释\n\n1. ok \n\n\u003e : 是否成功 2==ok\n\n2. status \n\n\u003e: 状态\n\n3. statusText\n\n\u003e 该请求的响应状态信息,包含一个状态码和原因短语 (例如 \"200 OK\"). 只读.\n\n4. url\n\n\u003e 该请求所要访问的URL\n\n5. clone\n\n\u003e 本函数\n\n6. text : `function`\n\n\u003e 返回异步-获取-「`String`类型」数据\n\n7. json : `function`\n\n\u003e 返回异步-获取-「`JSON`格式」数据\n\n8. blob : `function`\n\n\u003e 返回异步-获取-「`Blob`格式」数据\n\n9. headers : `object`\n\n    - keys : `function`\n\n    \u003e 返回 `[]` - `[key, key1,...]` 请求头\n\n    - entries : `function`\n\n    \u003e 返回 `[]` - `[[key, value],[key1, value1,..]` 请求头\n\n    - get : `function(n)`\n    \n    \u003e 返回 `string` headers[n] 请求头\n    \n\n    - has : `function`\n\n    \u003e 返回 `Boolean`,是否在请求头\n    \n---\n\n##","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchinanf-boy%2Fexplain-unfetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchinanf-boy%2Fexplain-unfetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchinanf-boy%2Fexplain-unfetch/lists"}