vue2.0版本后,推薦axios,vue1.X版本使用vue-resourse
Axios特點
1、瀏覽器中創建XMLHttpRequests
2、從node.js創建http請求
3、支持promise API
4、攔截請求和響應
5、轉換請求和響應數據
6、取消請求
7、自動轉換JSON
8、客戶端支持防御XSRF
Axios配置項(非常的重要)
{ // `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) { }) }
eg:config.js
export default{ url: '/get', baseURL: 'http://www.jiekou.cn', method: 'POST', transformRequest: [ function(data) { //進行一些加密操作等等,或者數據的轉換return data; } ], transformResponse: [ function(data) { return data; } ], headers: { 'Content-Type':'application/x-www-form-urlencoded' }, params: { }, paramsSerializer: function(params) { return Qs.stringify(params) }, timeout: 5000, withCredentials: false, // default responseType: 'json', // default //將upload事件注釋掉,防止跨域狀態下發起option請求 // onUploadProgress: function(progressEvent) { // // Do whatever you want with the native progress event // }, // onDownloadProgress: function(progressEvent) { // // Do whatever you want with the native progress event // }, maxContentLength: 2000, validateStatus: function(status) { return status >= 200 && status < 300; // default }, maxRedirects: 5, // default }
API:結合官網的案例
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]])
並發
處理並發請求的助手函數
axios.all(iterable)
axios.spread(callback)
可以使用自定義配置新建一個 axios 實例
axios.create([config])
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
在使用別名方法時, url
、method
、data
這些屬性都不必在配置中指定。
axios.all([方法1,方法2,方法3]).then(function(方法一返回,方法二返回,方法三返回){
})
<head> <title>axios - all example</title> <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> </head> <body class="container"> <h1>axios.all</h1> <div> <h3>User</h3> <div class="row"> <img id="useravatar" src="" class="col-md-1"/> <div class="col-md-3"> <strong id="username"></strong> </div> </div> <hr/> <h3>Orgs</h3> <ul id="orgs" class="list-unstyled"></ul> </div> <script src="../../dist/axios.min.js"></script> <script> axios.all([ axios.get('https://api.github.com/users/mzabriskie'), axios.get('https://api.github.com/users/mzabriskie/orgs') ]).then(axios.spread(function (user, orgs) { document.getElementById('useravatar').src = user.data.avatar_url; document.getElementById('username').innerHTML = user.data.name; document.getElementById('orgs').innerHTML = orgs.data.map(function (org) { return ( '<li class="row">' + '<img src="' + org.avatar_url + '" class="col-md-1"/>' + '<div class="col-md-3">' + '<strong>' + org.login + '</strong>' + '</div>' + '</li>' ); }).join(''); })); </script>
實現效果:
config的使用
<body class="container"> <h1>axios.all</h1> <div> <h3>User</h3> <div class="row"> <img id="useravatar" src="" class="col-md-1"/> <div class="col-md-3"> <strong id="username"></strong> </div> </div> <hr/> <h3>Orgs</h3> <ul id="orgs" class="list-unstyled"></ul> </div> <script src="../../dist/axios.min.js"></script> <script> var config={ baseURL: 'https://api.github.com/', transformRequest: [ function(data) { //進行一些加密操作等等,或者數據的轉換return data; return data } ], transformResponse: [ function(data) { return data; } ], headers: { 'Content-Type':'application/x-www-form-urlencoded' }, params: { }, timeout: 5000, withCredentials: false, // default responseType: 'json', // default //將upload事件注釋掉,防止跨域狀態下發起option請求 // onUploadProgress: function(progressEvent) { // // Do whatever you want with the native progress event // }, // onDownloadProgress: function(progressEvent) { // // Do whatever you want with the native progress event // }, maxContentLength: 2000, validateStatus: function(status) { return status >= 200 && status < 300; // default }, maxRedirects: 5, // default } var instance=axios.create(config); axios.all([ instance.get('/users/mzabriskie'), instance.get('/users/mzabriskie/orgs') ]).then(axios.spread(function (user, orgs) { document.getElementById('useravatar').src = user.data.avatar_url; document.getElementById('username').innerHTML = user.data.name; document.getElementById('orgs').innerHTML = orgs.data.map(function (org) { return ( '<li class="row">' + '<img src="' + org.avatar_url + '" class="col-md-1"/>' + '<div class="col-md-3">' + '<strong>' + org.login + '</strong>' + '</div>' + '</li>' ); }).join(''); })); </script> </body>
配置的默認值
1、全局的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';
2、自定義實例的默認值
// 創建實例時設置配置的默認值 var instance = axios.create({ baseURL: 'https://api.example.com' }); // 在實例已創建后修改默認值 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置的優先順序
配置會以一個優先順序進行合並。這個順序是:在 lib/defaults.js
找到的庫的默認值,然后是實例的 defaults
屬性,最后是請求的 config
參數。后者將優先於前者。這里是一個例子:
// 使用由庫提供的配置的默認值來創建實例 // 此時超時配置的默認值是 `0` var instance = axios.create(); // 覆寫庫的超時默認值 // 現在,在超時前,所有請求都會等待 2.5 秒 instance.defaults.timeout = 2500; // 為已知需要花費很長時間的請求覆寫超時設置 instance.get('/longRequest', { timeout: 5000 });
攔截器
在請求或響應被 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); });
// http request 攔截器 axios.interceptors.request.use( config => { if (store.state.token) { // 判斷是否存在token,如果存在的話,則每個http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); });
axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: 401 旌旗 靈醫 , 只用[授權] 旌旗的醫生 才是 靈醫 // 返回 401 清除token信息並跳轉到登錄頁面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的錯誤信息 });
錯誤處理
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); });