{"id":21461773,"url":"https://github.com/appletjs/netop","last_synced_at":"2025-03-17T04:50:00.969Z","repository":{"id":57150697,"uuid":"140084850","full_name":"appletjs/netop","owner":"appletjs","description":"Netop 是一个基于 promise 的 HTTP 库，目前可用在浏览器端。","archived":false,"fork":false,"pushed_at":"2018-08-29T09:39:00.000Z","size":25,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-26T03:36:03.730Z","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":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/appletjs.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-07-07T13:02:53.000Z","updated_at":"2018-08-29T09:39:01.000Z","dependencies_parsed_at":"2022-08-31T20:02:29.592Z","dependency_job_id":null,"html_url":"https://github.com/appletjs/netop","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/appletjs%2Fnetop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appletjs%2Fnetop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appletjs%2Fnetop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appletjs%2Fnetop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/appletjs","download_url":"https://codeload.github.com/appletjs/netop/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243976503,"owners_count":20377692,"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-11-23T07:10:53.372Z","updated_at":"2025-03-17T04:50:00.947Z","avatar_url":"https://github.com/appletjs.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Netop\n\n[![version](https://img.shields.io/npm/v/netop.svg?style=flat-square)](https://www.npmjs.com/package/netop)\n[![downloads](https://img.shields.io/npm/dt/netop.svg?style=flat-square)](https://www.npmjs.com/package/netop)\n\n\nNetop 是一个基于 promise 的 HTTP 库，目前可用在浏览器端。\n\n## 安装\n\n```bash\n$ npm i netop applet --save\n```\n\n```html\n\u003cscript src=\"//unpkg.com/applet\"\u003e\u003c/script\u003e\n\u003cscript src=\"//unpkg.com/netop\"\u003e\u003c/script\u003e\n```\n\n## Features\n\n- 基于 fetch 实现\n- 支持 Promise API\n- 拦截请求和响应\n- 客户端支持防御 XSRF\n\n\n## netop([init])\n\n是对 Netop 类的简单封装，方便调用。\n\n#### 简单使用\n\n```js\nnetop({url: '', method: ''}).send().then(function(response) {\n  // response 是原生 Response 的实例\n  // 你可以在这里验证 headers\n  response.headers.has('X-Respond-Token');\n  \n  // 获取响应的 JSON 数据\n  response.json().then(function(json) {});\n  // 如果需要多次使用，可以 clone 这个 response\n  response.clone().json().then(function(json) {});\n  response.clone().text().then(function(text) {});\n  response.clone().blob().then(function(blob) {});\n}).catch(function(err) {\n  // 错误处理，可能存在下面3个属性\n  // err.config - 配置信息\n  // err.request - 请求实例\n  // err.response - 响应实例\n})\n```\n\n#### 精细控制流程\n\n```js\nnetop()// 返回 Netop 类的实例\n  .use(function(config, next) {})// 使用配置拦截器\n  .with('/path/to')// 拦截器类型分水岭\n  .use(function(request, next) {})// 请求拦截器\n  .send()// 发起请求（在其后面设置拦截器，会触发异常终止程序）\n  .then(function(response) {})// 处理响应数据\n  .catch(function(err) {});// 捕获异常（来自拦截器或请求触发的）\n```\n\n\n## Netop\n\n#### constructor([init])\n\n- init\n  \n    - url `\u003cstring\u003e` | `\u003cFunction\u003e` 可选，定义我们想要fetch的资源。可以是下面两者之一:\n      \n        \u003e 1. 一个直接包含我们希望fetch的资源的URL的USVString;\n        \u003e 2. 一个 **Request** 对象.\n    \n    - body `\u003cany\u003e` 可选，任何你想加到请求中的body，可以是 **Blob**, **BufferSource**, **FormData**, **URLSearchParams**, 或 **USVString对象**。\n      \n        \u003e 需要注意的是 **GET** 和 **HEAD** 请求没有 body（若指定了值，会在创建请求时触发异常）。\n\n    - cache `\u003cstring\u003e` 可选，请求中想要使用的缓存模式，具体说明查看 \u003chttps://developer.mozilla.org/zh-CN/docs/Web/API/Request/cache\u003e，\n    有效值：**`default`**、**`no-store`**、**`reload`**、**`no-cache`**、**`force-cache`** 或 **`only-if-cached`**。\n    \n    - redirect `\u003cstring\u003e`  对重定向处理的模式。在Chrome中，Chrome 47 之前的版本默认值为 `manual` ，\n    自Chrome 47起，默认值为 `follow`。有效值：**`follow`**、**`error`**、**`manual`**。\n    \n    - credentials `\u003cstring\u003e` 可选，想要在请求中使用的credentials，浏览器默认值应该为 `omit`。\n    但在Chrome中，Chrome 47 之前的版本默认值为 `same-origin`，自Chrome 47起，默认值为 `include`。\n    自 Firefox 43后, 若URL有 credentials，Request() 会抛出TypeError, 例如 `http://user:password@example.com`。\n    根据规范，三个有效值: **`omit`**、**`same-origin**、**`include`**。\n                                  。\n    - headers `\u003cany\u003e` 可选，任何你想加到请求中的头。\n\n    - integrity `\u003cstring\u003e` 可选，包括请求的 subresource integrity 值。\n    e.g. `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`\n\n    - method `\u003cstring\u003e` 可选，请求方法，`Netop`做了内部校验，七个有效值：\n    **`GET`**、**`DELETE`**、**`POST`**、**`PUT`**、**`PATCH`**、**`HEAD`** 或 **`OPTIONS`**\n    \n    - mode `\u003cstring\u003e` 可选，请求的模式, 浏览器默认值应该为 cors。但在Chrome中，Chrome 47 之前的版本默认值为 `no-cors` ，\n    自Chrome 47起，默认值为 `same-origin`。有效值：**`same-origin`**、**`no-cors`**、**`cors`** 或 **`navigate`**。\n      \n    - referrer `\u003cstring\u003e` 可选，一个指定了 `no-referrer`、`client` 或一个 URL的 **USVString**。浏览器的默认值是 `client`.\n    \n    - auth `\u003cObject\u003e` 可选，Basic Authorization。\n      \n        - username `\u003cstring\u003e` 可选，用户名。\n        - password `\u003cstring\u003e` 可选，密码。\n    \n    - xsrf `\u003cObject\u003e`\n    \n        - cookieName `\u003cstring\u003e` 可选，保存在cookie中的值\n        - headerName `\u003cstring\u003e` 可选，将保存在cookie中的值映射到请求体的headers上面\n    \n    - validity `\u003cboolean\u003e` 可选，默认值 `true`，值为true时，校验 RequestInit 参数；只有通过校验，才会被用于请求。\n    - validateStatus `\u003cFunction\u003e` 可选，验证响应实例的状态码是否有效。\n    - adapter `\u003cFunction\u003e` 可选，发起请求的函数，默认值是 **`window.fetch`**。\n\n\n#### use(...fns): this\n\n使用拦截器（也可以称作中间件），具体参考中间件框架 **[applet](https://appletjs.github.io/applet/index.html)**。\n\n- fns `\u003cFunction[]\u003e`\n\n\n#### with(url): this\n\n该方法用于区分 use 的拦截器类型，即 use 的拦截器用于处理 config 还是 request。\n\n- url `\u003cstring\u003e` | `\u003cFunction\u003e` 可选，请求路径。\n\n```js\nnetop({})\n  // 使用配置拦截器\n  .use(function(config, next) {\n    // 修改配置信息\n    config.mode = 'no-cors';\n    config.integrity = 'sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=';\n    return next();\n  })\n  .with('/user?id=1234')// 拦截器类型分水岭\n  .use(function(request, next) {\n    // request 是 Request 的实例\n    if (request.headers.get('x-access-token') !== 'cached access token') {\n      throw new Error('Token失效');\n    }\n    return next();\n  })\n  .send()// 发起请求）\n  .then(response =\u003e response.json())\n  .then(function(result = {}) {\n    if (result.code !== 0) {\n      throw new Error(result.message || 'error message');\n    } \n  })\n  .catch(function(err) {});// 捕获异常\n```\n\n#### send([body]): Promise\u003cResponse\u003e\n\n发送数据到服务器，调用该方法后，就不能够再使用拦截器了；\n该方法返回一个 Promise\u003cResponse\u003e 实例；\n\n- body `\u003cany\u003e` 可选，提交的数据\n\n\n## netop.all(...promises)\n\n- `Array\u003cPromise\u003cany\u003e\u003e` promises\n\n## netop.spread(callback)\n\n- `function` callback\n\n\n\n## License\n\nMIT © 2018, \u003ca href=\"mailto:japplet@163.com\" title=\"japplet@163.com\"\u003eMaofeng Zhang\u003c/a\u003e","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fappletjs%2Fnetop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fappletjs%2Fnetop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fappletjs%2Fnetop/lists"}