axios的基礎(chǔ)使用

中文文檔: http://www.axios-js.com/

npm 倉庫地址: https://www.npmjs.com/package/axios

github地址: https://github.com/axios/axios

簡介

axios是基于promise用于瀏覽器和node.js的http客戶端

  • 1.支持瀏覽器和node.js
  • 2.支持promise
  • 3.能夠請求攔截和響應(yīng)
  • 4.能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
  • 5.能取消請求
  • 6.自動轉(zhuǎn)換為JSON數(shù)據(jù)
  • 7.瀏覽器端支持防止CSRF(跨站請求偽造)

安裝

  • 1.使用npm安裝
$ npm install axios
  • 2.使用bower
$ bower install axios
  • 3.使用CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

請求示例

  • 1.發(fā)送GET請求
// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


// 上面的請求也可以這樣做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 2.發(fā)送POST請求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 3.執(zhí)行多個并發(fā)請求
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) {
    // 兩個請求現(xiàn)在都執(zhí)行完成
  }));

axios的API

  • 1.axios(config)
// 發(fā)送 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
axios({
    method: 'get',
    url: 'https://cdn.gumt.top/blog_bg.jpg',
    responseType: 'stream'
})
.then(res => {
    res.data.pipe(fs.createWriteStream('blog_bg.jpg'))
})

我們甚至可以利用這個功能去做一些有趣的事情灵疮, 比如: 小型的爬蟲遍略。

  • 2.axios(url[,config])
// 發(fā)送一個GET請求(默認(rèn)的請求方式)
axios('/usre/123456');

并發(fā)請求

// iterable 一個可以迭代的參數(shù)如數(shù)組等
axios.all(iterable)
//callback要等到所有請求都完成才會執(zhí)行
axios.spread(callback)

請求方法別名

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]])

注意:我們使用別名方法去請求數(shù)據(jù)的時候, URL,Method,Data這個幾個參數(shù)不需要再配置中聲明烫罩。

創(chuàng)建一個axios實例

  • 1.axios.create([config])
let myFetch = axios.create({
    baseURL:"https://some-domain.com/api/",
    timeout:1000,
    headers: {'X-Custom-Header':'foobar'}
})
  • 2.實例方法

注意已定義的配置將和利用create創(chuàng)建的實例的配置合并

axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])

示例:

myFetch.get('getUser/1')
.then(res => {
    console.log(res)
})
// 這里實際發(fā)起的是  https://some-domain.com/api/getUser/1  get請求。

請求配置

下面的請求配置項织咧, 只有URL是必須的蠕趁,如果method 請求方法沒有定義,那么它默認(rèn)是以GET的方式發(fā)出的請求鲜屏。

{
   // `url` 是用于請求的服務(wù)器 URL
  url: '/user',


  // `method` 是創(chuàng)建請求時使用的方法
  method: 'get', // default


  // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL国拇。
  // 它可以通過設(shè)置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URL
  baseURL: 'https://some-domain.com/api/',


  // `transformRequest` 允許在向服務(wù)器發(fā)送前洛史,修改請求數(shù)據(jù)
  // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
  // 后面數(shù)組中的函數(shù)必須返回一個字符串,或 ArrayBuffer酱吝,或 Stream
  transformRequest: [function (data, headers) {
    // 對 data 進(jìn)行任意轉(zhuǎn)換處理
    return data;
  }],


  // `transformResponse` 在傳遞給 then/catch 前也殖,允許修改響應(yīng)數(shù)據(jù)
  transformResponse: [function (data) {
    // 對 data 進(jìn)行任意轉(zhuǎn)換處理
    return data;
  }],


  // `headers` 是即將被發(fā)送的自定義請求頭
  headers: {'X-Requested-With': 'XMLHttpRequest'},


  // `params` 是即將與請求一起發(fā)送的 URL 參數(shù)
  // 必須是一個無格式對象(plain object)或 URLSearchParams 對象
  params: {
    ID: 12345
  },


   // `paramsSerializer` 是一個負(fù)責(zé) `params` 序列化的函數(shù)
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },


  // `data` 是作為請求主體被發(fā)送的數(shù)據(jù)
  // 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'
  // 在沒有設(shè)置 `transformRequest` 時,必須是以下類型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬:FormData, File, Blob
  // - Node 專屬: Stream
  data: {
    firstName: 'Fred'
  },


  // `timeout` 指定請求超時的毫秒數(shù)(0 表示無超時時間)
  // 如果請求話費了超過 `timeout` 的時間务热,請求將被中斷
  timeout: 1000,


   // `withCredentials` 表示跨域請求時是否需要使用憑證
  withCredentials: false, // default


  // `adapter` 允許自定義處理請求忆嗜,以使測試更輕松
  // 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },


 // `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗證,并提供憑據(jù)
  // 這將設(shè)置一個 `Authorization` 頭崎岂,覆寫掉現(xiàn)有的任意使用 `headers` 設(shè)置的自定義 `Authorization`頭
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },


   // `responseType` 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型捆毫,可以是 '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` 是用作 xsrf token 的值的cookie的名稱
  xsrfCookieName: 'XSRF-TOKEN', // default


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


   // `onUploadProgress` 允許為上傳處理進(jìn)度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },


  // `onDownloadProgress` 允許為下載處理進(jìn)度事件
  onDownloadProgress: function (progressEvent) {
    // 對原生進(jìn)度事件的處理
  },


   // `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸
  maxContentLength: 2000,


  // `validateStatus` 定義對于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },


  // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目
  // 如果設(shè)置為0,將不會 follow 任何重定向
  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` 和 `httpsAgent` 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時使用的自定義代理佛寿。允許像這樣配置選項:
  // `keepAlive` 默認(rèn)沒有啟用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),


  // 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口
  // `auth` 表示 HTTP 基礎(chǔ)驗證應(yīng)當(dāng)用于連接代理濒憋,并提供憑據(jù)
  // 這將會設(shè)置一個 `Proxy-Authorization` 頭娘纷,覆寫掉已有的通過使用 `header` 設(shè)置的自定義 `Proxy-Authorization` 頭。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },


  // `cancelToken` 指定用于取消請求的 cancel token
  // (查看后面的 Cancellation 這節(jié)了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

響應(yīng)體結(jié)構(gòu)

{
  data:{},
  status:200,
  //從服務(wù)器返回的http狀態(tài)文本
  statusText:'OK',
  //響應(yīng)頭信息
  headers: {},
  //`config`是在請求的時候的一些配置信息
  config: {}
}

可以通過then鏈?zhǔn)讲僮鳙@取響應(yīng)信息

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

配置默認(rèn)值

可以指定將被用在各個請求的配置默認(rèn)值

全局的axios默認(rèn)值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定義實例默認(rèn)值

// 當(dāng)創(chuàng)建實例的時候配置默認(rèn)配置
const instance = axios.create({
  baseURL: 'https://api.example.com'
});
// 當(dāng)實例創(chuàng)建時候修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置優(yōu)先級

config配置將會以優(yōu)先級別來合并跋炕,順序是lib/defaults.js中的默認(rèn)配置,然后是實例中的默認(rèn)配置律适,最后是請求中的config參數(shù)配置辐烂,越往后等級越高,后面的會覆蓋前面的例子捂贿。

//創(chuàng)建一個實例的時候會使用libray目錄中的默認(rèn)配置
//在這里timeout配置的值為0纠修,來自于libray的默認(rèn)值
var instance = axios.create();
//回覆蓋掉library的默認(rèn)值
//現(xiàn)在所有的請求都要等2.5S之后才會發(fā)出
instance.defaults.timeout = 2500;
//這里的timeout回覆蓋之前的2.5S變成5s
instance.get('/longRequest',{
  timeout: 5000
});

攔截器

在請求或響應(yīng)被then或catch處理前攔截他們。

// 添加請求攔截器
axios.interceptors.request.use(function (config) {
    // 在發(fā)送請求之前做些什么
    return config;
  }, function (error) {
    // 對請求錯誤做些什么
    return Promise.reject(error);
  });


// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
    // 對響應(yīng)數(shù)據(jù)做點什么
    return response;
  }, function (error) {
    // 對響應(yīng)錯誤做點什么
    return Promise.reject(error);
  });

如果你想要移除攔截器厂僧,可以進(jìn)行如下操作扣草。

var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);

給自定義的axios實例添加攔截器

var myFetch = axios.create();
myFetch.interceptors.request.use(function(){}) // 請求攔截器
myFetch.interceptors.response.use(function(){}) // 響應(yīng)處理

示例:

let myFetch = axios({
    baseURL: "http://192.168.0.100:8080/api/",
    timeout: 5000
})
myFetch.interceptors.request.use(config => {
    let token = localStorage.getItem("token");
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
}, error => {
    return Promise.reject("Request failed"); 
})
/**
如果后端給我的數(shù)據(jù)格式如下:
{
status: xxx,  // 狀態(tài)碼
msg: '', // 提示信息
data: [], // 響應(yīng)數(shù)據(jù)
success: true // 是否成功
}
*/
myFetch..interceptors.response.use(res => {
    let {msg, status} = res.data;
    console.lg(msg);
    return res.data;
}, error => {
    return Promise.reject("Error, The error could be a network exception or a system exception");
})

錯誤處理

axios.get('/user/12345')
  .catch(function(error){
    if(error.response){
      //請求已經(jīng)發(fā)出,但是服務(wù)器響應(yīng)返回的狀態(tài)嗎不在2xx的范圍內(nèi)
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.header);
    }else {
      //一些錯誤是在設(shè)置請求的時候觸發(fā)
      console.log('Error',error.message);
    }
    console.log(error.config);
  });

取消請求

你可以通過一個cancel token來取消一個請求

你可以通過CancelToken.source工廠函數(shù)來創(chuàng)建一個cancel token

var CancelToken = axios.CancelToken;
var source = CancelToken.source();


axios.get('/user/12345',{
  cancelToken: source.token
}).catch(function(thrown){
  if(axios.isCancel(thrown)){
    console.log('Request canceled',thrown.message);
  }else {
    //handle error
  }
});


//取消請求(信息的參數(shù)可以設(shè)置的)
source.cance("操作被用戶取消");

你也可以給cancelToken構(gòu)造函數(shù)傳遞一個executor function來創(chuàng)建一個cancel token:

var cancelToken = axios.CancelToken;
var cance;
axios.get('/user/12345',{
  cancelToken: new CancelToken(function(c){
    //這個executor函數(shù)接受一個cancel function作為參數(shù)
    cancel = c;
  })
})
//取消請求
cancel();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末颜屠,一起剝皮案震驚了整個濱河市辰妙,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌甫窟,老刑警劉巖密浑,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異粗井,居然都是意外死亡尔破,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進(jìn)店門浇衬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懒构,“玉大人,你說我怎么就攤上這事耘擂〉ň纾” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵梳星,是天一觀的道長赞赖。 經(jīng)常有香客問我,道長冤灾,這世上最難降的妖魔是什么前域? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮韵吨,結(jié)果婚禮上匿垄,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好椿疗,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布漏峰。 她就那樣靜靜地躺著,像睡著了一般届榄。 火紅的嫁衣襯著肌膚如雪浅乔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天铝条,我揣著相機(jī)與錄音靖苇,去河邊找鬼。 笑死班缰,一個胖子當(dāng)著我的面吹牛贤壁,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播埠忘,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼脾拆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了莹妒?” 一聲冷哼從身側(cè)響起名船,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎旨怠,沒想到半個月后包帚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡运吓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年渴邦,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拘哨。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡谋梭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出倦青,到底是詐尸還是另有隱情瓮床,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布产镐,位于F島的核電站隘庄,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏癣亚。R本人自食惡果不足惜丑掺,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望述雾。 院中可真熱鬧街州,春花似錦兼丰、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至面徽,卻和暖如春艳丛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背趟紊。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工质礼, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人织阳。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像砰粹,于是被迫代替她去往敵國和親唧躲。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360