理解 ajax、fetch和axios

背景
  • ajax
  • fetch、axios
優缺點
  • ajax基於jquery,引入時需要引入龐大的jquery庫,不符合當下前端框架,於是fetch替代了ajax

  • 由於fetch是比較底層,需要我們再次封裝,比如data參數配置

    // jquery ajax
    $.post(url, {name: 'test'})
    // fetch
    fetch(url, {
        method: 'POST',
        body: Object.keys({name: 'test'}).map((key) => {
            return encodeURIComponent(key) + '=' + ncodeURIComponent(params[key]);
        }).join('&')
    })
    
  • fetch不支持超時控制,即timeout

詳解axios

axios是什麼

基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中

axios的特點

1. 從瀏覽器中創建 XMLHttpRequests
2. 從 node.js 創建 http 請求
3. 支持 Promise API支持 Promise API
4. 攔截請求和響應 (就是有interceptor,攔截器)
5. 轉換請求數據和響應數據
6. 取消請求
7. 自動轉換 JSON 數據
8. 客戶端支持防禦 XSRF

攔截器原理

攔截器

兼容性

火狐 谷歌 ie Edge safari

安裝

npm install axios

用法

//執行get請求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});

// Optionally the request above could also be done as
axios.get('/user', {
 params: {
   ID: 12345
 }
}).then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});

使用流程

//首先創建一個Axios實例
var axiosIns = axios.create({
    baseURL: '請求地址',
    timeout: 延時時長,
    headers: {'X-product': 'h5'}
})
//設置request攔截器
axiosIns.interceptors.request.use(request=>{
    //處理request,可以對所有請求統一處理請求頭等
})
//response攔截器
axiosIns.interceptors.response.use(response=>{
    //處理response,可以對所有響應做處理
})

//實例方法
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]])

//請求配置
{
  baseURL: 'https://www.tomandjerry.club/api/',
    url: '/user',
    method: 'get',
    //transformRequest 允許在向服務器發送前,修改請求數據,
    //只能用在PUT POST PATCH 這幾個請求方法中,
    //後面的數組中的函數必須返回一個字符串,或ArrayBuffer,或Stream
    transformRequst: [function(data){
        //對data進行任意轉換處理
        return data;
    }],
    //transformResponse 在傳遞給then/catch 前,允許修改響應數據
    transformResponse: [function(data){
        //對data進行任意轉換處理
    }],
    //自定義請求頭
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    //params 必須是一個 無格式對象 或 URLSearchParams對象
    params: {
        ID: 1234
    },
    //paramsSerializer 是負責params序列化的函數
    //什麼是序列化和反序列化,見下
    paramsSerializer: function(params){
        return Qs.strinfify(params,{arrayFormat: 'brackets'})
    },
    //data 主體的發送數據
    //只適用於PUT POST 和PATCH
    //在沒有設置transformRequest時,必須是以下類型之一
    //string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    //瀏覽器專屬:FomData,File,Blob
    //Node專屬:Stream
    data: {
        firstName: 'Jack'
    },
    //timeout 請求超時,如果請求超過了timeout指定的時間則請求將被中斷
    timeout: 1000,
    //表示跨域請求時是否需要使用憑證
    withCredentials: false,//默認的
    //adapter 允許自定義處理請求,使測試更輕鬆
    //返回 一個promise並應用一個有效的響應
    adapter: function(config){
        
    },
    //auth 表示應該使用HTTP基礎驗證,並提供憑據
    //將設置一個Authorization頭,覆寫掉現有的任意使用headers設置的自定義Authorization頭
    auth: {
        username: 'janedoe',
        password: 'ssss'
    },
    //responseType 表示服務器響應的數據類型,
    //可以是arraybuffer blob document json text stream
    responseType: 'json',//默認
    //xsrfCookieName 是用作xsrf token 的值的cookie的名稱
    xsrfCookieName: 'XSRF-TOKEN',//默認
    //xsrfHeaderName 是承載xsrf token 的值的HTTP頭的名稱
    xsrfHeaderName: 'X-XSRF-TOKEN', // 默認
    //onUploadProgress 允許爲上傳處理進度事件
    onUploadProgress: function(progressEvent){
        // 對原生進度事件的處理
    },
    //onDownloadProgress 允許爲下載處理進度事件
    onDownloadProgress: function(progressEvent){
        //對原生進度事件的處理
    },
    //maxContentLength 定義允許的響應內容的最大尺寸
    maxContentLength: 2000,
    //validateStatus 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject  
    //如果validateStatus返回true(或者設置爲 `null` 或 `undefined`),
    //promise 將被 resolve; 否則,promise 將被 rejecte
    validateStatus: function (status) {
        return status >= 200 && status < 300; // 默認
     },
     //maxRedirects 定義在 node.js 中 follow 的最大重定向數目
     // 如果設置爲0,將不會 follow 任何重定向
     maxRedirects: 5, // 默認的
     //httpAgent和httpsAgent分別在node.js中用於定義在執行http和https 時使用的自定義代理。
     //允許像這樣配置選項:keepAlive默認沒有啓用
     httpAgent: new http.Agent({ keepAlive: true }),
     httpsAgent: new https.Agent({ keepAlive: true }),
     //proxy定義代理服務器的主機名稱和端口,auth表示HTTP基礎驗證應當用於連接代理,並提供憑據
     //這將會設置一個Proxy-Authorization頭,
     //覆寫掉已有的通過使用header設置的自定義Proxy-Authorization頭。
     proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: : {
          username: 'mikeymike',
          password: 'rapunz3l'
        }
      },
      //cancelToken 指定用於取消請求的 cancel token
     cancelToken: new CancelToken(function (cancel) {
     
      })
}
序列化

解釋

在程序運行的過程中,所有變量都是存在內存中
d = dict(name='Bob', age=20, score=88)
可以隨時修改變量,比如把name改成'Bill',但是一旦程序結束,所有變量所佔用的內存就會被操作系統回收,下次重新運行變量又被重新初始化爲'Bob',我們把變量從內存中變成可儲存或傳輸的過程稱之爲序列化。在Python中叫pickling,在其他語言中也被稱之爲serialization,marshalling,flattening等等。序列化之後,就可以把序列化後的內容寫入磁盤,或者通過網絡傳輸到別的機器上。反之把變量內容從序列化的對象重新讀到內存裏稱之爲反序列化,即unpickling。
參考

https://www.jianshu.com/p/065294e2711c

https://github.com/axios/axios

https://juejin.im/post/5acde23c5188255cb32e7e76

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143192607210600a668b5112e4a979dd20e4661cc9c97000

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章