axios使用

axios

  • 基於promise用於瀏覽器和node.js的http客戶端

特色

  • 支持瀏覽器和node.js
  • 支持promise
  • 能攔截請求和響應
  • 能轉換請求和響應數據
  • 能取消請求
  • 自動轉換JSON數據
  • 瀏覽器端支持防止CSRF(跨站請求僞造)

1、安裝

  • npm安裝vue

    $ npm install axios
      npm install axios --save//本地
      npm install axios -s
  • 在vue中全局引用
  • 以vue-cli爲例,在main.js中
  • 由於axios並非vue自帶的,因此咱們不能用Vue.use()
  • 只能將其賦值給vue的prototype,已達到全部頁面都能使用axios的目的node

    import axios from 'axios';
      Vue.prototype.axios = axios;
  • 使用this.axiosjquery

    methods:{
          myajax:function(){
              this.axios({
                  method:'post',
                  url: '接口地址',
                  data:{}
              })
              .then(function(res){
                  console.log(res.data)
              })
              .catch(function(err){
                  console.log(err)
              })
          }
      }
  • bower安裝ios

    $ bower install axios
  • 經過cdn引入git

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

2、請求方法別名

爲了方便咱們爲全部支持的請求方法均提供了別名。

  • 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]])
  • 註釋:當使用以上別名方法時,url,method和data等屬性不用在config重複聲明。

3、get請求

傳參使用params

  • 官網上是axios.get我在項目中要加this.axios,因此後面都寫的this.axiosgithub

    方法1:
    this.axios.get('/user?ID=12345')
        .then(function (res) {
          console.log(res);
        })
        .catch(function (err) {
          console.log(err);
        });
方法2:
this.axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (err) {
    console.log(err);
  });
方法3,使用axiox API
this.axios({
  method:'get',
  url:'',
  params: {
      ID: 12345
  },
  responseType:'stream'
})
.then(function(response) {
     console.log(response);
})
.catch(function (error) {
    console.log(error);
  });

4、post請求

(1)、傳參使用data

方法1:
this.axios.post('url', {
    firstName: 'Fred',//屬性:屬性值
    lastName: 'Flintstone'
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (err) {
    console.log(err);
  });
方法2 axios API:
axios({
  method: 'post',
  url: '',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (res) {
    console.log(res);
  })
 .catch(function (err) {
    console.log(err);
  });

(2)、執行多個併發請求

this.axios.all([

      this.axios.get('url'),

      this.axios.get('url')

])
.then(this.axios.spread(function (userResp, reposResp) {

      // 上面兩個請求都完成後,才執行這個回調方法

      console.log('User', userResp.data);

      console.log('Repositories', reposResp.data);

  }));

(3)、同時發生的請求

如下兩個用來處理同時發生多個請求的輔助函數
  • axios.all(iterable)
  • axios.spread(callback)

5、axios API

(1)、詳解API中的配置

{
  // `url` 是用於請求的服務器 URL
  url: '/user',

  // `method` 是建立請求時使用的方法
  method: 'get', // 默認是 get

  // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
  // 它能夠經過設置一個 `baseURL` 便於爲 axios 實例的方法傳遞相對 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 容許在向服務器發送前,修改請求數據
  // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
  // 後面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data) {
    // 對 data 進行任意轉換處理

    return data;
  }],

  // `transformResponse` 在傳遞給 then/catch 前,容許修改響應數據
  transformResponse: [function (data) {
    // 對 data 進行任意轉換處理

    return data;
  }],

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

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

  // `paramsSerializer` 是一個負責 `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` 是做爲請求主體被髮送的數據
  // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'
  // 在沒有設置 `transformRequest` 時,必須是如下類型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬:FormData, File, Blob
  // - Node 專屬: Stream
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定請求超時的毫秒數(0 表示無超時時間)
  // 若是請求話費了超過 `timeout` 的時間,請求將被中斷
  timeout: 1000,

  // `withCredentials` 表示跨域請求時是否須要使用憑證
  withCredentials: false, // 默認的

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

  // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
  // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` 表示服務器響應的數據類型,能夠是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 默認的

  // `xsrfCookieName` 是用做 xsrf token 的值的cookie的名稱
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的

  // `onUploadProgress` 容許爲上傳處理進度事件
  onUploadProgress: function (progressEvent) {
    // 對原生進度事件的處理
  },

  // `onDownloadProgress` 容許爲下載處理進度事件
  onDownloadProgress: function (progressEvent) {
    // 對原生進度事件的處理
  },

  // `maxContentLength` 定義容許的響應內容的最大尺寸
  maxContentLength: 2000,

  // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject  promise 。若是 `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
  // (查看後面的 Cancellation 這節瞭解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

post

get

(2)、響應結構

1.某個請求的響應包含如下信息
{
  // `data` 由服務器提供的響應
  data: {},

  // `status` 來自服務器響應的 HTTP 狀態碼
  status: 200,

  // `statusText` 來自服務器響應的 HTTP 狀態信息
  statusText: 'OK',

  // `headers` 服務器響應的頭
  headers: {},

  // `config` 是爲請求提供的配置信息
  config: {}
}

2.使用then時,你將接收下面這樣的響應:
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);
  });

6、 建立一個axios實例而且能夠自定義其配置

(1)、axios.create([config])

var instance = axios.create({
  baseURL:"https://some-domain.com/api/",
  timeout:1000,
  headers: {'X-Custom-Header':'foobar'}
});

(2)、配置的默認值/defaults

  • 你能夠指定被用在各個請求的配置默認值

(3)、全局的axios默認值

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';

(4)、自定義實例默認值

// 建立實例時設置配置的默認值
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 在實例已建立後修改默認值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

(5)、配置的優先順序

  • 配置會以一個優先順序進行合併。這個順序是:在 lib/defaults.js 找到的庫的默認值,而後是實例的 defaults 屬性,最後是請求的 config 參數。後者將優先於前者。ajax

    // 使用由庫提供的配置的默認值來建立實例
      // 此時超時配置的默認值是 `0`
      var instance = axios.create();
    
      // 覆寫庫的超時默認值
      // 如今,在超時前,全部請求都會等待 2.5 秒
      instance.defaults.timeout = 2500;
    
      // 爲已知須要花費很長時間的請求覆寫超時設置
      instance.get('/longRequest', {
        timeout: 5000
      });

(6)、攔截器

1.在請求或響應被then或catch處理前攔截它們
// 添加請求攔截器
axios.interceptors.request.use(function (config) {
    // 在發送請求以前作些什麼
    return config;
  }, function (error) {
    // 對請求錯誤作些什麼
    return Promise.reject(error);
  });

// 添加響應攔截器
axios.interceptors.response.use(function (response) {
    // 對響應數據作點什麼
    return response;
  }, function (error) {
    // 對響應錯誤作點什麼
    return Promise.reject(error);
  });
2.若是你想在稍後移除攔截器,能夠這樣
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
3.能夠爲自定義axios實例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

(7)、錯誤處理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 請求已發出,但服務器響應的狀態碼不在 2xx 範圍內
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
1.能夠使用validateStatus配置選項定義一個自定義HTTP狀態碼的錯誤範圍。
axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 狀態碼在大於或等於500時纔會 reject
  }
})

(8)、取消

1.使用cancel token取消請求
2.能夠使用 CancelToken.source 工廠方法建立 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 {
    // 處理錯誤
  }
});

// 取消請求(message 參數是可選的)
source.cancel('Operation canceled by the user.');
3.還能夠經過傳遞一個 executor 函數到 CancelToken 的構造函數來建立 cancel token:
var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函數接收一個 cancel 函數做爲參數
    cancel = c;
  })
});

// 取消請求
cancel();
  • 注意: 能夠使用同一個 cancel token 取消多個請求
相關文章
相關標籤/搜索