axios

axios是基于promise的用于瀏覽器和nodejs的HTTP客戶(hù)端,本身有以下特征:
1.從瀏覽器中創(chuàng)建XMLHttpRequest;
2.從nodejs發(fā)出http請(qǐng)求
3.支持promiseAPI
4.攔截 請(qǐng)求和響應(yīng)
5.轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)
6.取消請(qǐng)求
7.自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
8.客戶(hù)端支持防止CSRF/XSRF攻擊

初始化一些常用的配置項(xiàng)

axios.defaults.baseURL = 'https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp';

axios.interceptors.response.use(result => result.data);
//=>設(shè)置響應(yīng)攔截器:分別在響應(yīng)成功和失敗的時(shí)候做一些攔截處理(在執(zhí)行成功后設(shè)定的方法之前,先會(huì)執(zhí)行攔截器中的方法)

axios.defaults.validateStatus = function validateStatus(status) {
 //=>自定義成功失敗規(guī)則:RESOLVE / REJECT(默認(rèn)規(guī)則:狀態(tài)碼以2開(kāi)頭算作成功)
      return /^(2|3)\d{2}$/.test(status);
};

 //=>設(shè)置在POST請(qǐng)求中基于請(qǐng)求主體向服務(wù)器發(fā)送內(nèi)容的格式,默認(rèn)是RAW,項(xiàng)目中常用的是URL-ENCODEED格式
axios.defaults.headers['Content-Type'] = 'appliction/x-www-form-urlencoded';

axios.defaults.transformRequest = data => {
    //=>DATA:就是請(qǐng)求主體中需要傳遞給服務(wù)器的內(nèi)容(對(duì)象)
    let str = ``;
    for (let attr in data) {
        if (data.hasOwnProperty(attr)) {
            str += `${attr}=${data[attr]}&`;
        }
    }
    return str.substring(0, str.length - 1);
};

使用方式示例
1.執(zhí)行g(shù)et數(shù)據(jù)請(qǐng)求

axios.get('url',{
  params:{
    id:'接口配置參數(shù)(相當(dāng)于url?id=xxxx)',
  },
}).then(function(res){
  console.log(res);//處理成功的函數(shù) 相當(dāng)于success
}).catch(function(error){
  console.log(error)//錯(cuò)誤處理 相當(dāng)于error
})

2.執(zhí)行post數(shù)據(jù)發(fā)送

axios.post('uel',{data:xxx},{
  headers:xxxx,
}).then(function(res){
  console.log(res);//處理成功的函數(shù) 相當(dāng)于success
}).catch(function(error){
  console.log(error)//錯(cuò)誤處理 相當(dāng)于error
})

3.axios API 通過(guò)相關(guān)配置傳遞給axios完成請(qǐng)求

axios({
  method:'delete',
  url:'xxx',
  cache:false,
  params:{id:123},
  headers:xxx,
})
//------------------------------------------//
axios({
  method: ’post’,
  url: ’/user/12345’,
  data: {
    firstName: ’Fred’,
    lastName: ’Flintstone’
  }
});

axios的并發(fā)(axios.all,axios.spread)

let axiosList=[
   axios.get('url1',{params:xxx,dateType:'JSON'}),
   axios.get('url2',{params:xxx,dateType:'TEXT'}),
]
axios.all(axiosList).then(axios.spread(function(res1,res2){
  console.log(res1,res2)//分別是兩個(gè)請(qǐng)求的返回值
})

axios包含所有請(qǐng)求方式函數(shù)的封裝

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]])
當(dāng)使用別名方法時(shí),不需要在config中指定url,method和data屬性。

創(chuàng)建實(shí)例

var instance = axios.create({//初始化數(shù)據(jù)
  baseURL: ’https://some-domain.com/api/’,
  timeout: 1000,
  headers: {’X-Custom-Header’: ’foobar’}
});

axios請(qǐng)求配置項(xiàng)

1. `url`是將用于請(qǐng)求的服務(wù)器URL
url: ‘/user’,
2. `method`是發(fā)出請(qǐng)求時(shí)使用的請(qǐng)求方法
method: ‘get’, // 默認(rèn)
3. `baseURL`將被添加到`url`前面,除非`url`是絕對(duì)的。
// 可以方便地為 axios 的實(shí)例設(shè)置`baseURL`,以便將相對(duì) URL 傳遞給該實(shí)例的方法。
baseURL: ‘https://some-domain.com/api/’, 
4. `transformRequest`允許在請(qǐng)求數(shù)據(jù)發(fā)送到服務(wù)器之前對(duì)其進(jìn)行更改
// 這只適用于請(qǐng)求方法’PUT’,’POST’和’PATCH’
// 數(shù)組中的最后一個(gè)函數(shù)必須返回一個(gè)字符串,一個(gè) ArrayBuffer或一個(gè) Stream 
transformRequest: [function (data) {
// 做任何你想要的數(shù)據(jù)轉(zhuǎn)換 然后  return data;
}], 
5. `transformResponse`允許在 then / catch之前對(duì)響應(yīng)數(shù)據(jù)進(jìn)行更改
transformResponse: [function (data) {
  // 做任何你想要的數(shù)據(jù)轉(zhuǎn)換 然后  return data;
}], 
6. `headers`是要發(fā)送的自定義 headers
headers: {‘X-Requested-With’: ’XMLHttpRequest’},
7. `params`是要與請(qǐng)求一起發(fā)送的URL參數(shù)
// 必須是純對(duì)象或URLSearchParams對(duì)象
params: {
  ID: 12345
}, 
8.  `paramsSerializer`是一個(gè)可選的函數(shù),負(fù)責(zé)序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
  return Qs.stringify(params, {arrayFormat: ’brackets’})
}, 
9. `data`是要作為請(qǐng)求主體發(fā)送的數(shù)據(jù)
// 僅適用于請(qǐng)求方法“PUT”,“POST”和“PATCH”
// 當(dāng)沒(méi)有設(shè)置`transformRequest`時(shí),必須是以下類(lèi)型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
  firstName: ’Fred’
}, 
10. `timeout`指定請(qǐng)求超時(shí)之前的毫秒數(shù)。
// 如果請(qǐng)求的時(shí)間超過(guò)’timeout’,請(qǐng)求將被中止。
timeout: 1000,
11.  `withCredentials`指示是否跨站點(diǎn)訪(fǎng)問(wèn)控制請(qǐng)求
withCredentials: false, // default
12.  `adapter’允許自定義處理請(qǐng)求,這使得測(cè)試更容易。
// 返回一個(gè)promise并提供一個(gè)有效的響應(yīng)(參見(jiàn)[response docs](#response-api))
adapter: function (config) {
/* … */
}, 
13.  `auth’表示應(yīng)該使用 HTTP 基本認(rèn)證,并提供憑據(jù)。
// 這將設(shè)置一個(gè)`Authorization’頭,覆蓋任何現(xiàn)有的`Authorization’自定義頭,使用`headers`設(shè)置。
auth: {
  username: ’janedoe’,
  password: ’s00pers3cret’
}, 
14.  “responseType”表示服務(wù)器將響應(yīng)的數(shù)據(jù)類(lèi)型
// 包括 ‘a(chǎn)rraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’
responseType: ‘json’, // default 
15. `xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱(chēng)
xsrfCookieName: ‘XSRF-TOKEN’, // default 
16.  `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱(chēng)
xsrfHeaderName: ‘X-XSRF-TOKEN’, // default 
17.  `onUploadProgress`允許處理上傳的進(jìn)度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
}, 
18.  `onDownloadProgress`允許處理下載的進(jìn)度事件
onDownloadProgress: function (progressEvent) {
}, 
19.  `maxContentLength`定義允許的http響應(yīng)內(nèi)容的最大大小
maxContentLength: 2000, 
20.  `validateStatus`定義是否解析或拒絕給定的promise
// HTTP響應(yīng)狀態(tài)碼。如果`validateStatus`返回`true`(或被設(shè)置為`null` promise將被解析;否則,promise將被
  // 拒絕。
validateStatus: function (status) {
  return status >= 200 && status < 300; // default
}, 
21.  `maxRedirects`定義在node.js中要遵循的重定向的最大數(shù)量。
// 如果設(shè)置為0,則不會(huì)遵循重定向。
maxRedirects: 5, // 默認(rèn) 
22.  `httpAgent`和`httpsAgent`用于定義在node.js中分別執(zhí)行http和https請(qǐng)求時(shí)使用的自定義代理。
// 允許配置類(lèi)似`keepAlive`的選項(xiàng),
// 默認(rèn)情況下不啟用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), 
23.  ‘proxy’定義代理服務(wù)器的主機(jī)名和端口
// `auth`表示HTTP Basic auth應(yīng)該用于連接到代理,并提供credentials。
// 這將設(shè)置一個(gè)`Proxy-Authorization` header,覆蓋任何使用`headers`設(shè)置的現(xiàn)有的`Proxy-Authorization` 自定義 headers。
proxy: {
  host: ’127.0.0.1’,
  port: 9000,
  auth: : {
    username: ’mikeymike’,
    password: ’rapunz3l’
  }
}, 
24.  “cancelToken”指定可用于取消請(qǐng)求的取消令牌
cancelToken: new CancelToken(function (cancel) {
})
}

收到如下響應(yīng)數(shù)據(jù)

console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);

初步封裝一個(gè)類(lèi)似于axios的函數(shù)
需求
1.執(zhí)行返回一個(gè)promise對(duì)象
2.能夠通過(guò)create方法配置初始化參數(shù)
3.包含所有的ajax的方法并返回promise對(duì)象
4.支持peomise.all并能用spread處理

(function () {
    function myAxios(options = {}) {
        myAxios.createDef = myAxios.createDef || {};
        myAxios._default = {
            method: 'GET',
            url: '',
            baseURL: '',
            cache: false,
            data: null,
            params: null,
            headers: {},
            dataType: 'JSON',
        }
        let {method,url,baseURL,cache,data,params,headers,dataType}={...myAxios._default, ...myAxios.createDef,...options};
        if (/^(get|delete|head|options)$/i.test(method)) {//get系列
            if (params) {
                url += /\?/g.test(url) ? '&' + myAxios.paramsSerializer(params) : '?' + myAxios.paramsSerializer(params);
            }
            if (cache === false) {
                url += /\?/g.test(url) ? '&_=' + new Date() : '?_=' + new Date();
            }
        } else {
            if (data) {
                data = myAxios.paramsSerializer(data);
            }
        }
        ;
        return new Promise(function (resolve, reject) {
            let xhr = new XMLHttpRequest();
            xhr.open(method, `${baseURL}${url}`);
            if (headers && typeof headers == 'object') {
                for (let attr in headers) {
                    if (!headers.hasOwnProperty(attr)) {
                        let val = /[\u4e00-\u9fa5]/.test(headers[attr]) ? encodeURIComponent(headers[attr]) : headers[attr];
                        xhr.setRequestHeader(attr, val);
                    }
                }
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (/2\d{2}/.test(xhr.status)) {
                        let result = xhr.responseText;
                        dataType = dataType.toUpperCase();
                        dataType === 'JSON' ? result = JSON.parse(result) : (dataType === 'XML' ? result = xhr.responseXML : null);
                        resolve(result);
                    } else {
                        reject('error');
                    }
                }
            }
            xhr.send(data);
        })
    };
    myAxios.paramsSerializer = function (params) {
        if (typeof params == 'string') {
            return params;
        }
        if (!params) {
            return null;
        }
        if (typeof params == 'object') {
            let res = '';
            res=Object.keys(params).reduce((pre,next,index)=>{
              return pre+"&"+`${next}=${params[next]}`;
            },"").substring(1);
            return res;
        }
    };
    myAxios.all = function (data) {
        return Promise.all(data);
    };
    myAxios.spread = function (callback) {
        return function (arg) {
            callback.apply(null, arg);
        }
    };
    myAxios.create = function (options) {
        if (options && typeof options == 'object') {
            myAxios.createDef = options;
        }
    };

    ['get', 'delete', 'head', 'options'].forEach(item => {
        myAxios[item] = function (url, options = {}) {
            options = {
                ...options,
                url: url,
                method: item.toUpperCase()
            };
            return myAxios(options);
        }
    });
    ['post', 'put', 'patch'].forEach(item => {
        myAxios[item] = function (url, data = {}, options = {}) {
            options = {
                ...options,
                url: url,
                method: item.toUpperCase(),
                data: data,
            };
            return myAxios(options);
        }
    });
window.myAxios=myAxios;
})()

轉(zhuǎn)載自:http://www.itdecent.cn/p/93fa30986d07

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容