{"id":20414462,"url":"https://github.com/x-extends/xe-ajax","last_synced_at":"2025-04-12T16:44:46.701Z","repository":{"id":57401207,"uuid":"115435566","full_name":"x-extends/xe-ajax","owner":"x-extends","description":"fetch 异步请求库，用于浏览器和 node.js 的 HTTP 客户端","archived":false,"fork":false,"pushed_at":"2021-11-14T13:07:30.000Z","size":722,"stargazers_count":33,"open_issues_count":0,"forks_count":12,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-26T11:11:11.256Z","etag":null,"topics":["xe-ajax"],"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/x-extends.png","metadata":{"files":{"readme":"README.en-US.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":"2017-12-26T15:55:39.000Z","updated_at":"2024-07-09T09:50:29.000Z","dependencies_parsed_at":"2022-09-19T04:50:19.549Z","dependency_job_id":null,"html_url":"https://github.com/x-extends/xe-ajax","commit_stats":null,"previous_names":[],"tags_count":83,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/x-extends%2Fxe-ajax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/x-extends%2Fxe-ajax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/x-extends%2Fxe-ajax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/x-extends%2Fxe-ajax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/x-extends","download_url":"https://codeload.github.com/x-extends/xe-ajax/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248600346,"owners_count":21131467,"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":["xe-ajax"],"created_at":"2024-11-15T06:10:10.760Z","updated_at":"2025-04-12T16:44:46.682Z","avatar_url":"https://github.com/x-extends.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# xe-ajax\n\n[简体中文](README.md) | English  \n\n[![gitee star](https://gitee.com/x-extends/xe-ajax/badge/star.svg?theme=dark)](https://gitee.com/x-extends/xe-ajax/stargazers)\n[![npm version](https://img.shields.io/npm/v/xe-ajax.svg?style=flat-square)](https://www.npmjs.com/package/xe-ajax)\n[![npm build](https://travis-ci.com/x-extends/xe-ajax.svg?branch=master)](https://travis-ci.com/x-extends/xe-ajax)\n[![npm downloads](https://img.shields.io/npm/dm/xe-ajax.svg?style=flat-square)](http://npm-stat.com/charts.html?package=xe-ajax)\n[![gzip size: JS](http://img.badgesize.io/https://unpkg.com/xe-ajax/dist/xe-ajax.umd.min.js?compression=gzip\u0026label=gzip%20size:%20JS)](http://img.badgesize.io/https://unpkg.com/xe-ajax/lib/xe-utils.umd.min.js?compression=gzip\u0026label=gzip%20size:%20JS)\n[![npm license](https://img.shields.io/github/license/mashape/apistatus.svg)](LICENSE)\n\n[fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) based asynchronous request function for the browser and node.js HTTP client.\n\n## Browser Support\n\nxe-ajax Depends on a native [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) implementation to be supported. If your environment doesn't support Promises, you can babel-polyfill or bluebird.js.\n\n![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_7-8/internet-explorer_7-8_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png)\n--- | --- | --- | --- | --- | --- |\n8+ ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 6.1+ ✔ |\n\n## Installing\n\n```shell\nnpm install xe-ajax --save\n```\n\n```javascript\nimport XEAjax from 'xe-ajax'\nimport XEAjaxMock from 'xe-ajax-mock'\n\nXEAjax.use(XEAjaxMock)\n```\n\nUsing nodejs\n\n```javascript\nconst XEAjax = require('xe-ajax')\n```\n\nGet on [unpkg](https://unpkg.com/xe-ajax/) and [cdnjs](https://cdn.jsdelivr.net/npm/xe-ajax/)\n\n```javascript\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/xe-ajax\"\u003e\u003c/script\u003e\n```\n\n## API\n\n* Core\n  * [ajax ( request )](#ajax)\n  * [fetch ( url[, request] )](#fetch-to-response)\n* Function 1\n  * [doJsonp ( url[, params, request] )](#jsonp)\n  * [doGet ( url[, params, request] )](#fetch-to-response-schema-v340)\n  * [doPost ( url[, body, request] )](#fetch-to-response-schema-v340)\n* Function 2\n  * [jsonp ( url[, params, request] )](#jsonp)\n  * [get ( url[, params, request] )](#fetch-to-json)\n  * [post ( url[, body, request] )](#fetch-to-json)\n\n### Request\n\n*: Only modern browsers are supported.\n\n| Name | Type | Description | default value |\n|------|------|-----|----|\n| url | String | Request interface contains the URL of the request. |  |\n| baseURL | String | Request base URL |  |\n| method | String | The method read-only property of the Request interface contains the request's method | 'GET' |\n| params | Object | Request the params contents. |  |\n| body | Object | Request the body contents. |  |\n| bodyType | String | Submit type, You can set: json-data,form-data | 'json-data' |\n| mode | String | The mode you want to use for the request, You can set: cors,no-cors,same-origin | 'cors' |\n| cache | String | Handling cache mode, You can set: default,no-store,no-cache,reload,force-cache,only-if-cached | 'default' |\n| credentials | String | Set the cookie to be sent along with the request, You can set: omit,same-origin,include | 'same-origin' |\n| jsonp | String | set jsonp Callback parameter name. | 'callback' |\n| jsonpCallback | String | Set jsonp callback function name. | Default is a random number with json_xeajax_ prefix |\n| timeout | Number | Setting the request timeout. |  |\n| headers | Object | Optional header fields. | {'Accept': 'application/json, text/plain, */*'} |\n| origin | String | Change the origin. | location.origin |\n| transformParams | Function (params,request) | Change the URL parameter before sending the request. |  |\n| paramsSerializer | Function (params,request) | The custom URL serialization function is finally spliced in the URL. | XEAjax.serialize |\n| transformBody | Function (body,request) | Change the commit body before sending the request. |  |\n| stringifyBody | Function (body,request) | Customize the body stringify function. | JSON.stringify |\n| validateStatus | Function (response) | Verify that the request is successful. | 200-299 |\n| ***redirect** | String | The redirect mode to use, You can set: follow,error,manual | 'follow' |\n| ***referrer** | String | Specifies the value of the referer HTTP header. You can set: no-referrer,client,URL | 'client' |\n| ***referrerPolicy** | String | You can set: no-referrer,no-referrer-when-downgrade,origin,origin-when-cross-origin,unsafe-url |  |\n| ***keepalive** | String | The keepalive option can be used to allow the request to outlive the page. |  |\n| ***integrity** | String | Contains the subresource integrity value of the request. |  |\n\n### Headers\n\n| Name | Type | Description |\n|------|------|-----|\n| set | Function (name,value) | Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist. |\n| append | Function (name,value) | Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist. |\n| get | Function (name) | Returns a ByteString sequence of all the values of a header within a Headers object with a given name. |\n| has | Function (name) | Returns a boolean stating whether a Headers object contains a certain header. |\n| delete | Function (name) | Deletes a header from a Headers object. |\n| keys | Function | Returns an iterator allowing you to go through all keys of the key/value pairs contained in this object. |\n| values | Function | Returns an iterator allowing you to go through all values of the key/value pairs contained in this object. |\n| entries | Function | Returns an iterator allowing to go through all key/value pairs contained in this object. |\n| forEach | Function (callback,context) | Executes a provided function once for each array element. |\n\n### Response\n\n| Name | Type | Description |\n|------|------|-----|\n| body | ReadableStream | The body read-only property of the Body mixin is a simple getter used to expose a ReadableStream of the body contents. |\n| bodyUsed | Boolean | The bodyUsed read-only property of the Body mixin contains a Boolean that indicates whether the body has been read yet. |\n| headers | Headers | The headers read-only property of the Response interface contains the Headers object associated with the response. |\n| status | Number | The status read-only property of the Response interface contains the status code of the response. |\n| statusText | String | The statusText read-only property of the Response interface contains the status message corresponding to the status code. |\n| url | String | The url read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects.  |\n| ok | Boolean | The ok read-only property of the Response interface contains a Boolean stating whether the response was successful. |\n| redirected | Boolean | The read-only redirected property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. |\n| type | String | The type read-only property of the Response interface contains the type of the response. |\n| clone | Function | Creates a clone of a Response object. |\n| json | Function | Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. |\n| text | Function | Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). |\n| blob | Function | Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. |\n| arrayBuffer | Function | Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. |\n| formData | Function | Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. |\n\n## Default Global Settings\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nXEAjax.setup({\n  // origin: 'https://test.com',\n  // baseURL: 'https://test.com',\n  bodyType: 'json-data',\n  credentials: 'include',\n  headers: {\n    'Accept': 'application/json, text/plain, \\*/\\*;'\n  },\n  validateStatus (response) {\n    return response.status \u003e= 200 \u0026\u0026 response.status \u003c 300\n  },\n  transformParams (params, request) {\n    if (request.method === 'GET') {\n      params.queryDate = params.queryDate.getTime()\n    }\n    return params\n  },\n  paramsSerializer (params, request) {\n    return XEUtils.serialize(params)\n  }，\n  transformBody (body, request) {\n    body.startTime = body.startDate.getTime()\n    return body\n  },\n  stringifyBody (body, request) {\n    return JSON.stringify(body)\n  }\n})\n```\n\n## Examples\n\n### ajax\n\n```JavaScript\nconst XEAjax = require('xe-ajax')\n\nXEAjax.ajax({\n  url: '/api/test/message/list',\n  method: 'GET',\n  params: {\n    id: 1\n  }\n})\n  .then(response =\u003e {\n    if (response.ok) {\n      // success\n    } else {\n      // failed\n    }\n  }).catch(e =\u003e {\n    // error\n    console.log(e.message)\n  })\n```\n\n### fetch to Response\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nXEAjax.fetch('/api/test/message/save', {\n  method: 'POST',\n  body: {\n    name: 'test'\n  }\n})\n  .then(response =\u003e {\n    if (response.ok) {\n      // success\n    } else {\n      // failed\n    }\n  }).catch(e =\u003e {\n    // error\n    console.log(e.message)\n  })\n\n// Response Text\nXEAjax.fetch('/api/test/message/list')\n  .then(response =\u003e {\n    response.text().then(text =\u003e {\n      // text\n    })\n  })\n\n// Response JSON\nXEAjax.fetchGet('/api/test/message/list')\n  .then(response =\u003e {\n    response.json().then(data =\u003e {\n      // data\n    })\n  })\n\n// Response Blob\nXEAjax.fetch('/api/test/message/list')\n  .then(response =\u003e {\n    response.blob().then(blob =\u003e {\n      // blob\n    })\n  })\n\n// Response ArrayBuffer\nXEAjax.fetch('/api/test/message/list')\n  .then(response =\u003e {\n    response.arrayBuffer().then(arrayBuffer =\u003e {\n      // arrayBuffer\n    })\n  })\n\n// Response FormData\nXEAjax.fetch('/api/test/message/list')\n  .then(response =\u003e {\n    response.formData().then(formData =\u003e {\n      // formData\n    })\n  })\n\n// Submit 'application/json'\nlet body1 = {\n  name: 'u111',\n  password: '123456'\n}\nXEAjax.fetchPost('/api/test/message/save', body1, {bodyType: 'json-data'})\n\n// Submit 'application/x-www-form-urlencoded'\nlet body2 = {\n  name: 'u222',\n  password: '123456'\n}\nXEAjax.fetchPost('/api/test/message/save', body2, {bodyType: 'form-data'})\n\n// Submit \"application/x-www-form-urlencoded\"\nlet searchParams = new URLSearchParams();\nsearchParams.append('name', 'u222');\nsearchParams.append('content', '123456');\nXEAjax.fetchPost('/api/test/message/save', searchParams);\n\n// Submit 'multipart/form-data'\nlet file = document.querySelector('#myFile').files[0]\nlet formData = new FormData()\nformData.append('file', file)\nXEAjax.fetchPost('/api/test/message/save', formData)\n\n// Submit body and query params.\nXEAjax.fetchPost('/api/test/message/save', {name: 'u333',password: '123456'}, {params: {id: 111}})\n\nXEAjax.fetchGet('/api/test/message/list')\nXEAjax.fetchPut('/api/test/message/update', {name: 'u222'})\nXEAjax.fetchDelete('/api/test/message/delete/1')\n```\n\n### fetch to Response Schema (v3.4.0+)\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// The response for a request contains the following information.\n// Result =\u003e {data, status, statusText, headers}\n\n// The completion or failure is based on state check.\nXEAjax.doGet('/api/test/message/list').then(result =\u003e {\n  // success result.data\n}).catch(result =\u003e {\n  // failed\n})\n\nXEAjax.doGet('/api/test/message/list/page/15/1')\nXEAjax.doPost('/api/test/message/save', {name: 'u111'})\nXEAjax.doPut('/api/test/message/update', {name: 'u222'})\nXEAjax.doDelete('/api/test/message/delete/1')\n```\n\n### fetch to JSON\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// The completion or failure is based on state check.\nXEAjax.get('/api/test/message/list').then(data =\u003e {\n  // success\n}).catch(data =\u003e {\n  // failed\n})\n\nXEAjax.get('/api/test/message/list/page/15/1').then(({page, result}) =\u003e {\n  // success\n})\n\nXEAjax.post('/api/test/message/save', {name: 'test'})\nXEAjax.post('/api/test/message/save', {name: 'test', password: '123456'}, {bodyType: 'json-data'})\nXEAjax.post('/api/test/message/save', {name: 'test', password: '123456'}, {bodyType: 'form-data'})\n\nlet file = document.querySelector('#myFile').files[0]\nlet formBody = new FormData()\nformBody.append('file', file)\nXEAjax.post('/api/test/message/save', formBody)\n```\n\n### jsonp\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// Case 1:\n// http://test.com/api/jsonp/public/message?callback=jsonp_xeajax_1521272815608_1\n// jsonp_xeajax_1521272815608_1({message: 'success'})\nXEAjax.fetchJsonp('/api/jsonp/public/message')\n  .then(response =\u003e {\n    if (response.ok) {\n      response.json().then(data =\u003e {\n        // data\n      })\n    }\n  })\n\n// Case 2:\n// http://test.com/api/jsonp/public/message?cb=jsonp_xeajax_1521272815608_2\n// jsonp_xeajax_1521272815608_2({message: 'success'})\nXEAjax.doJsonp('/api/jsonp/public/message', null, {jsonp: 'cb'})\n  .then(response =\u003e {\n    // response.data\n  })\n\n// Case 3:\n// http://test.com/api/jsonp/public/message?id=222\u0026cb=func\n// func({message: 'success'})\nXEAjax.jsonp('/api/jsonp/public/message', {id: 222}, {jsonp: 'cb',jsonpCallback: 'func'})\n  .then(data =\u003e {\n    // data\n  })\n```\n\n### Multiple Requests\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nPromise.all([\n  XEAjax.fetchGet('/api/test/message/list'),\n  XEAjax.doGet('/api/test/message/list'),\n  XEAjax.post('/api/test/message/save'), {name: 'n1'})\n]).then(datas =\u003e {\n  // all finish\n}).catch(e =\u003e {\n  // error\n})\n\nPromise.race([\n  XEAjax.get('/api/test/message/list'),\n  XEAjax.get('/api/test/message/list')\n]).then(datas =\u003e {\n  // finish\n}).catch(e =\u003e {\n  // error\n})\n\n// doAll Use object parameters, The use is consistent with that of Promise.\nlet iterable2 = []\niterable2.push({url: '/api/test/message/list'})\niterable2.push({url: '/api/test/message/save', body: {name: 'n1'}}, method: 'POST'})\nXEAjax.doAll(iterable2).then(datas =\u003e {\n  // all finish\n}).catch(e =\u003e {\n  // error\n})\n```\n\n### Nested Requests\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// This should be avoided in the project.\nXEAjax.fetchGet('/api/test/message/info', {id: 3})\n  .then(response =\u003e response.json())\n  .then(data =\u003e XEAjax.fetchGet(`/api/test/message/delete/${data.id}`))\n  .then(response =\u003e {\n    if (response.ok) {\n      response.json().then(data =\u003e {\n        // data\n      })\n    }\n  })\nXEAjax.doGet('/api/test/message/info', {id: 3})\n  .then(result =\u003e XEAjax.doGet(`/api/test/message/delete/${result.data.id}`))\n  .then(result =\u003e {\n    // result.data\n  })\nXEAjax.get('/api/test/message/info', {id: 3})\n  .then(data =\u003e XEAjax.get(`/api/test/message/delete/${data.id}`))\n  .then(data =\u003e {\n    // data\n  })\n```\n\n## Promises, async/await\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nasync function init() {\n  let list = await XEAjax.get('/api/test/message/list')\n  let data = await XEAjax.get('/api/test/message/info', {id: list[0].id})\n  console.log(list)\n  console.log(data)\n}\n\ninit()\n```\n\n## Upload/Download (v3.4.9+)\n\n| Name | Type | Description |\n|------|------|-----|\n| onUploadProgress | Function (event) | Upload progress |\n| onDownloadProgress | Function (event) | Download progress |\n| meanSpeed | Number | Default 0 off,Set the rate to equalization mode and calculate the average rate every millisecond. |\n| fixed | Number | default 2 |\n\n### Progress\n\n| Name | Type | Description |\n|------|------|-----|\n| autoCompute | Boolean | Whether to automatically calculate. |\n| value | Number | Current progress % |\n| loaded | Object | Transmitted size {value, size, unit} |\n| total | Object | Total size {value, size, unit} |\n| speed | Object | Transmission speed/s {value, size, unit} |\n| remaining | Number | RemainingTime/s |\n| time | Number | timestamp |\n\nListener request progress.\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nlet file = document.querySelector('#myFile').files[0]\nlet formBody = new FormData()\nformBody.append('file', file)\nXEAjax.fetchPost('/api/upload', formBody)\nXEAjax.doPost('/api/upload', formBody)\nXEAjax.post('/api/upload', formBody)\n\n\n// Upload\n// Create a Progress.\nlet progress = new XEAjax.Progress()\nprogress.onUploadProgress = evnt =\u003e {\n  let value = progress.value\n  let loadedSize = progress.loaded.size\n  let loadedUnit = progress.loaded.unit\n  let totalSize = progress.total.size\n  let totalUnit = progress.total.unit\n  let speedSize = progress.speed.size\n  let speedUnit = progress.speed.unit\n  let remaining = progress.remaining\n  console.log(`Progress:${value}% ${loadedSize}${loadedUnit}${totalSize}/${totalUnit}; Speed:${speedSize}/${speedUnit}s; Remaining:${remaining}s`)\n}\nlet file = document.querySelector('#myFile').files[0]\nlet formBody = new FormData()\nformBody.append('file', file)\nXEAjax.fetchPost('/api/upload', formBody, {progress})\n// Progress:1% 176KB/14.26MB; Speed:1.69MB/s; Remaining:8s\n// Progress:3% 368KB/14.26MB; Speed:640KB/s; Remaining:22s\n// Progress:8% 1.16MB/14.26MB; Speed:1.56MB/s; Remaining:8s\n// ...\n// Progress:99% 14.08MB/14.26MB; Speed:119.6KB/s; Remaining:2s\n// Progress:100% 14.26MB/14.26MB; Speed:114.4KB/s; Remaining:0s\n\n\n// Download\n// Create Progress object.\nlet progress = new XEAjax.Progress()\nprogress.onDownloadProgress = evnt =\u003e {\n  let value = progress.value\n  let loadedSize = progress.loaded.size\n  let loadedUnit = progress.loaded.unit\n  let totalSize = progress.total.size\n  let totalUnit = progress.total.unit\n  let speedSize = progress.speed.size\n  let speedUnit = progress.speed.unit\n  let remaining = progress.remaining\n  console.log(`Progress:${value}% ${loadedSize}${loadedUnit}${totalSize}/${totalUnit}; Speed:${speedSize}/${speedUnit}s; Remaining:${remaining}s`)\n}\nXEAjax.fetchGet('/api/download/file/1', {progress, method: 'GET'})\n```\n\n## Cancel request (v3.2.0+)\n\n### AbortController\n\nAllows control of one or more cancellation requests.\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// Create a controller.\nlet controller = new XEAjax.AbortController()\nlet signal = controller.signal\n// Associate the signal and controller with the fetch request.\nXEAjax.fetchGet('/api/test/message/list', {id: 1}, {signal})\n  .then(response =\u003e {\n    // finish\n  }).catch(function (e) {\n    // error\n  })\nsetTimeout(() =\u003e {\n  controller.abort()\n}, 50)\n```\n\n## Interceptor (v3.0+)\n\n### Request interceptor\n\nXEAjax.interceptors.request.use(Function(request, next))\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// Trigger before the request is sent.\nXEAjax.interceptors.request.use((request, next) =\u003e {\n  // Can be used for unified permission intercept, set request header, Token authentication, parameters, etc.\n\n  // Set params\n  // Request.params.version = Date.now()\n\n  // Set Token validation to prevent XSRF/CSRF attacks.\n  request.headers.set('X-Token', cookie('x-id'))\n\n  // Call next(), execute the next interceptor.\n  next()\n})\n```\n\n### Response interceptor\n\nXEAjax.interceptors.response.use(Function(response, next[, request]), Function(response, next[, request]))\n\nnext( [, newResponse] )\n\n| Name | Type | Description |\n|------|------|-----|\n| status | Number | Setting the status code of the response. |\n| statusText | String | Setting the status message corresponding to the status code. |\n| body | Object | Setting the body contents. |\n| headers | Headers、Object | Setting the Headers object associated with the response. |\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\n// Intercept when the request is finish.\nXEAjax.interceptors.response.use((response, next) =\u003e {\n  // It can be used for unified processing after a request is finish, such as checking for invalidation, message prompt, special scenario processing, etc.\n\n  // Example: check login failover.\n  if (response.status === 403) {\n    router.replace({path: '/login'})\n    // Break up\n  } else {\n    // Call next(), execute the next interceptor.\n    next()\n  }\n})\n\n// Intercept and change the response data after the request is complete.\nXEAjax.interceptors.response.use((response, next) =\u003e {\n  response.json().then(data =\u003e {\n    let { status, statusText, headers } = response\n    let body = {\n      message: status === 200 ? 'success' : 'error',\n      result: data\n    }\n    // Change the response data and continue with the next interceptor.\n    next({status, statusText, headers, body})\n  })\n}, (e, next) =\u003e {\n  // Turn all the exception errors to finish.\n  let body = {\n    message: 'error',\n    result: null\n  }\n  // Change the response data and continue with the next interceptor.\n  next({status: 200, body})\n})\n```\n\n## mixin ( fns )\n\nExtends its own utility functions to XEAjax.\n\n```JavaScript\nimport XEAjax from 'xe-ajax'\n\nXEAjax.mixin({\n  get (url, request) {\n    return XEAjax.doGet(url, null, request)\n  },\n  delete (url, request) {\n    return XEAjax.doDelete(url, request)\n  },\n  post (url, data, request) {\n    return XEAjax.doPost(url, data, request)\n  },\n  put (url, data, request) {\n    return XEAjax.doPut(url, data, request)\n  }\n})\n\nXEAjax.get('/api/test/message/list', {params: {id: 123}})\nXEAjax.delete('/api/test/message/delete/123')\nXEAjax.post('/api/test/message/save', {name: 'test1'})\nXEAjax.put('/api/test/message/update', {id: 123, name: 'test1'})\n```\n\n## License\n\n[MIT](LICENSE) © 2017-present, Xu Liangzhan\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fx-extends%2Fxe-ajax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fx-extends%2Fxe-ajax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fx-extends%2Fxe-ajax/lists"}