Axios文檔摘要

[官方參考](https://github.com/axios/axios

安裝

npm i axios
//cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

特性

  • 瀏覽器端 XHR 請求
  • http in nodejs
  • 支持 Promise
  • 攔截請求 及響應
  • 自動轉換 json
  • 取消請求
  • 支持 XSRF

例子

GET

axios.get('/user?id=111')
  .then(function(res){
   console.log(res)
}
  .catch(function(res){
  console.log(res)
}

axios.get('/user',{
  params:{
    id:111
  }
  })
  .then(function(res){ console.log(res) }
  .catch(function(res){ console.log(res)}

async function getUser(){
  try {
      const res = await axios.get('/user?id=111')
      console.log(res)
  }catch(err){
    console.log(err)
  }
}

POST

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

并發(fā)請求執(zhí)行

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

API

axios(config)

axios({
  method: 'post',
  url: '/user',
  data: {
    a: '1',
    b: '2'
  }
};
//發(fā)送一個默認的 GET 請求
axios('/user');

別名方法
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

并發(fā)api

axios.all(iterable)
axios.spread(callback)

創(chuàng)建實例

axios.create(config)
實例會繼承別名方法
實例基礎配置會合并指定配置

請求配置詳解

{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000,

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}

響應概要

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

自定義配置 見參考 Config Defaults

配置的優(yōu)先級

攔截器

請求取消

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末起意,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子感论,更是在濱河造成了極大的恐慌院塞,老刑警劉巖椅寺,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件浇冰,死亡現(xiàn)場離奇詭異殊霞,居然都是意外死亡畸悬,警方通過查閱死者的電腦和手機歧蕉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進店門灾部,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人惯退,你說我怎么就攤上這事赌髓。” “怎么了催跪?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵春弥,是天一觀的道長。 經常有香客問我叠荠,道長,這世上最難降的妖魔是什么扫责? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任榛鼎,我火速辦了婚禮,結果婚禮上鳖孤,老公的妹妹穿的比我還像新娘者娱。我一直安慰自己,他們只是感情好苏揣,可當我...
    茶點故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布黄鳍。 她就那樣靜靜地躺著,像睡著了一般平匈。 火紅的嫁衣襯著肌膚如雪框沟。 梳的紋絲不亂的頭發(fā)上藏古,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機與錄音忍燥,去河邊找鬼拧晕。 笑死,一個胖子當著我的面吹牛梅垄,可吹牛的內容都是我干的厂捞。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼队丝,長吁一口氣:“原來是場噩夢啊……” “哼靡馁!你這毒婦竟也來了?” 一聲冷哼從身側響起机久,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤臭墨,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后吞加,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體裙犹,經...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年衔憨,在試婚紗的時候發(fā)現(xiàn)自己被綠了叶圃。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡践图,死狀恐怖掺冠,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情码党,我是刑警寧澤德崭,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站揖盘,受9級特大地震影響眉厨,放射性物質發(fā)生泄漏。R本人自食惡果不足惜兽狭,卻給世界環(huán)境...
    茶點故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一憾股、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧箕慧,春花似錦服球、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至伐庭,卻和暖如春粉渠,著一層夾襖步出監(jiān)牢的瞬間分冈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工渣叛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留丈秩,地道東北人。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓淳衙,卻偏偏與公主長得像蘑秽,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子箫攀,可洞房花燭夜當晚...
    茶點故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理肠牲,服務發(fā)現(xiàn),斷路器靴跛,智...
    卡卡羅2017閱讀 134,599評論 18 139
  • 時間2017-03-31 13:43:44Hope’s Blog 原文https://blog.ygxdxx.co...
    蕭玄辭閱讀 15,185評論 3 16
  • 一梢睛、安裝 1肥印、 利用npm安裝npm install axios --save 2、 利用bower安裝bower...
    kiddings閱讀 1,745評論 0 3
  • 我寫東西不是為了什么绝葡,只是想把腦子里的東西騰個地方深碱,我的目標就是每天每篇幾百字,也說不上哪天就爛尾了藏畅,太監(jiān)了敷硅,故事...
    賭狗末日閱讀 156評論 2 3
  • 什么是IT行業(yè)?在IT行業(yè)就要學無止境嗎愉阎?很多人不了解這個行業(yè)绞蹦,IT行業(yè)官方解釋:信息技術產業(yè),又稱信息產業(yè)榜旦,它是...
    搵食艱難閱讀 178評論 0 0