{"id":19746780,"url":"https://github.com/cweili/req-json","last_synced_at":"2025-08-22T12:35:45.528Z","repository":{"id":22931223,"uuid":"97709902","full_name":"Cweili/req-json","owner":"Cweili","description":"Promise based simple HTTP/HTTPS client for browser to request JSON or string for RESTful apis, with koa-like middleware support.","archived":false,"fork":false,"pushed_at":"2024-09-23T21:36:03.000Z","size":161,"stargazers_count":4,"open_issues_count":3,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-30T14:18:52.752Z","etag":null,"topics":["ajax","http","https","json","middleware","promise","request","restful-api","weapp","wechat","wx","xhr","xmlhttprequest"],"latest_commit_sha":null,"homepage":"https://req-json.github.io/","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/Cweili.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2017-07-19T11:43:11.000Z","updated_at":"2024-06-27T02:52:44.000Z","dependencies_parsed_at":"2024-06-20T19:24:41.357Z","dependency_job_id":null,"html_url":"https://github.com/Cweili/req-json","commit_stats":{"total_commits":133,"total_committers":5,"mean_commits":26.6,"dds":"0.18796992481203012","last_synced_commit":"9a2447b2d7bafdbfa0777c5199d379d0953333bf"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cweili%2Freq-json","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cweili%2Freq-json/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cweili%2Freq-json/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cweili%2Freq-json/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Cweili","download_url":"https://codeload.github.com/Cweili/req-json/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224202778,"owners_count":17272807,"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","http","https","json","middleware","promise","request","restful-api","weapp","wechat","wx","xhr","xmlhttprequest"],"created_at":"2024-11-12T02:15:54.121Z","updated_at":"2024-11-12T02:15:54.709Z","avatar_url":"https://github.com/Cweili.png","language":"JavaScript","readme":"# req-json\n\n[![npm][badge-version]][npm]\n[![bundle size][badge-size]][bundlephobia]\n[![npm downloads][badge-downloads]][npm]\n[![license][badge-license]][license]\n\n\n[![github][badge-issues]][github]\n[![build][badge-build]][workflows]\n[![coverage][badge-coverage]][coveralls]\n\n\nPromise based simple HTTP/HTTPS client for browser to request JSON or string for RESTful apis, with koa-like middleware support.\n\n[Documents and examples](https://req-json.github.io/).\n\n## Installation\n\n### NPM\n\n```\nnpm install req-json --save\n```\n\n```js\nimport ReqJSON from 'req-json';\n```\n\n### Browser\n\nDirect `\u003cscript\u003e` include\n\n```html\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/req-json@2\"\u003e\u003c/script\u003e\n```\n\n### Wechat mini program (weapp)\n\n```js\nconst ReqJSON = require('req-json/dist/req-json.wx');\n```\n\nor just [download](https://cdn.jsdelivr.net/npm/req-json@2/dist/req-json.wx.js) and copy to your project.\n\n## Basic Usage\n\n```js\nimport ReqJSON from 'req-json';\n\nconst reqJSON = new ReqJSON();\n\nreqJSON.get('/api/item/:id', { id: 1 })\n  .then((item) =\u003e {});\n```\n\n## Shorthand methods\n\n```js\nasync getItem(id) {\n  let item;\n  try {\n    item = await reqJSON.get('/api/item/:id', { id });\n  } catch (err) {\n    console.error(err);\n  }\n  return item;\n}\n\nasync updateItem(item) {\n  try {\n    await reqJSON.post('/api/item/:id', item);\n  } catch (err) {\n    console.error(err);\n  }\n}\n```\n\n## RESTful API\n\n```js\nconst resource = reqJSON.resource('/api/item/:id');\n\nasync getItem(id) {\n  let item;\n  try {\n    item = await resource.get({ id });\n  } catch (err) {\n    console.error(err);\n  }\n  return item;\n}\n\nasync updateItem(item) {\n  try {\n    await resource.post(item);\n  } catch (err) {\n    console.error(err);\n  }\n}\n```\n\n## Methods\n\nSupports `GET` `POST` `PUT` `DELETE` methods.\n\n```js\nconst resource = reqJSON.resource('/api/item/:id');\n\nasync request() {\n  try {\n    const response = await resource.get({ id: 1 });\n    await resource.post({\n      id: 1,\n      others: { foo: 'bar' }\n    });\n    await resource.put({\n      id: 1,\n      others: { foo: 'bar' }\n    });\n    await resource.delete({ id: 1 });\n  } catch (err) {\n    console.error(err);\n  }\n}\n```\n\n## Options\n\nYou can set option for ReqJSON instance / resource defination / each single request.\n\n* `headers`: Customized request headers\n* `timeout`: Set request timeout\n\n### Set option for ReqJSON instance\n\n```js\nconst options = {\n  headers: {\n    Authorization: 'abc'\n  },\n  timeout: 1000\n};\nconst reqJSON = new ReqJSON(options);\n```\n\n### Set option for resource defination.\n\n```js\nconst options = {\n  headers: {\n    Authorization: 'abc'\n  },\n  timeout: 1000\n};\nconst resource = reqJSON.resource('/api/item/:id', options);\n\nasync request() {\n  try {\n    await resource.get({ id: 1 });\n  } catch (err) {\n    console.error(err);\n  }\n}\n```\n\n### Set option for single request.\n\n```js\nasync request() {\n  const options = {\n    headers: {\n      Authorization: 'abc'\n    },\n    timeout: 1000\n  };\n  try {\n    await resource.get({ id: 1 }, options);\n  } catch (err) {\n    console.error(err);\n  }\n}\n```\n\n## Middlewares\n\nSupports two diffrent kinds of functions as middleware:\n\n* async function\n* common function\n\n### Async function ([Can I use](http://caniuse.com/#feat=async-functions))\n\n```js\nreqJSON.use(async(context, next) =\u003e {\n  const start = Date.now();\n  await next();\n  const ms = Date.now() - start;\n  console.log(`${context.method} ${context.url} ${ms}ms`);\n});\n```\n\n### Common function\n\n```js\nreqJSON.use((context, next) =\u003e {\n  const start = Date.now();\n  return next()\n    .then(() =\u003e {\n      const ms = Date.now() - start;\n      console.log(`${context.method} ${context.url} ${ms}ms`);\n    });\n});\n```\n\n### Context\n\nContext contains these attributes:\n\n```ts\n/**\n * The path to use for the request, with parameters defined.\n */\npath: string\n\n/**\n * The HTTP method to use for the request (e.g. \"POST\", \"GET\", \"PUT\", \"DELETE\").\n */\nmethod: 'POST' | 'GET' | 'PUT' | 'DELETE'\n\n/**\n * The URL to which the request is sent.\n */\nurl: string\n\n/**\n * The data to be sent.\n */\ndata: any\n\n/**\n * The options to use for the request.\n */\noptions: object\n\n/**\n * The HTTP status of the response. Only available when the request completes.\n */\nstatus?: number\n\n/**\n * The parsed response. Only available when the request completes.\n */\nresponse?: any\n\n/**\n * The request headers before the request is sent, the response headers when the request completes.\n */\nheaders: Headers\n\n/**\n * Alias to `headers`\n */\nheader: Headers\n\n/**\n * The original XMLHttpRequest object.\n */\nxhr: XMLHttpRequest\n```\n\n### Reject when status 4xx or 5xx\n\n#### Async function\n\n```js\nreqJSON.use(async(context, next) =\u003e {\n  await next();\n  if (context.status \u003e= 400) {\n    throw new Error(context.response);\n  }\n});\n```\n\n#### Common function\n\n```js\nreqJSON.use((context, next) =\u003e {\n  return next()\n    .then(() =\u003e {\n      if (context.status \u003e= 400) {\nthrow new Error(context.response);\n      }\n    });\n});\n```\n\n### Set request headers and get response headers\n\n#### Async function\n\n```js\nreqJSON.use(async(context, next) =\u003e {\n  // set request headers\n  context.headers = {\n    'If-None-Match': 'abcdefg'\n  };\n  await next();\n  // get response headers\n  console.log(context.headers.etag);\n});\n```\n\n#### Common function\n\n```js\nreqJSON.use((context, next) =\u003e {\n  // set request headers\n  context.headers = {\n    'If-None-Match': 'abcdefg'\n  };\n  return next()\n    .then(() =\u003e {\n      // get response headers\n      console.log(context.headers.etag);\n    });\n});\n```\n\n[badge-version]: https://img.shields.io/npm/v/req-json.svg\n[badge-downloads]: https://img.shields.io/npm/dt/req-json.svg\n[npm]: https://www.npmjs.com/package/req-json\n\n[badge-size]: https://img.shields.io/bundlephobia/minzip/req-json.svg\n[bundlephobia]: https://bundlephobia.com/result?p=req-json\n\n[badge-license]: https://img.shields.io/npm/l/req-json.svg\n[license]: https://github.com/Cweili/req-json/blob/master/LICENSE\n\n[badge-issues]: https://img.shields.io/github/issues/Cweili/req-json.svg\n[github]: https://github.com/Cweili/req-json\n\n[badge-build]: https://img.shields.io/github/workflow/status/Cweili/req-json/ci/master\n[workflows]: https://github.com/Cweili/req-json/actions/workflows/ci.yml?query=branch%3Amaster\n\n[badge-coverage]: https://img.shields.io/coveralls/github/Cweili/req-json/master.svg\n[coveralls]: https://coveralls.io/github/Cweili/req-json?branch=master\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcweili%2Freq-json","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcweili%2Freq-json","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcweili%2Freq-json/lists"}