在Vue1.0的時候有一個官方推薦的 ajax 插件 vue-resource,但是自從 Vue 更新到 2.0 之後,官方就不再更新 vue-resource。
關于為什麼放棄推薦? -> 尤大原話
最近團隊讨論了一下,Ajax 本身跟 Vue 并沒有什麼需要特别整合的地方,使用 fetch polyfill 或是 axios、superagent 等等都可以起到同等的效果,
vue-resource 提供的價值和其維護成本相比并不劃算,是以決定在不久以後取消對 vue-resource 的官方推薦。已有的使用者可以繼續使用,
但以後不再把 vue-resource 作為官方的 ajax 方案。這裡可以去掉 vue-resource,文檔也不必翻譯了。
目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求,下面來具體介紹一下axios的使用。
axios 簡介
axios 是一個基于Promise 用于浏覽器和 nodejs 的 HTTP 用戶端,它本身具有以下特征:
- 從浏覽器中建立 XMLHttpRequest
- 從 node.js 發出 http 請求
- 支援 Promise API
- 攔截請求和響應
- 轉換請求和響應資料
- 取消請求
- 自動轉換JSON資料
- 用戶端支援防止 CSRF/XSRF
引入方式:
$ npm install axios
//使用淘寶源
$ cnpm install axios
//或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
安裝其他插件的時候,可以直接在 main.js 中引入并使用 Vue.use()來注冊,但是 axios并不是vue插件,是以不能 使用Vue.use(),是以隻能在每個需要發送請求的元件中即時引入。
為了解決這個問題,我們在引入 axios 之後,通過修改原型鍊,來更友善的使用。
//main.js
import axios from 'axios'
Vue.prototype.$http = axios
在 main.js 中添加了這兩行代碼之後,就能直接在元件的 methods 中使用 $http指令
methods: {
postData () {
this.$http({
method: 'post',
url: '/user',
data: {
name: 'xiaoming',
info: '12'
}
})
}
下面來介紹axios的具體使用:
執行 GET 請求
// 向具有指定ID的使用者送出請求
$http.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通過 params 對象傳遞參數
$http.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行 POST 請求
$http.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行多個并發請求
function getUserAccount() {
return $http.get('/user/12345');
}
function getUserPermissions() {
return $http.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then($http.spread(function (acct, perms) {
//兩個請求現已完成
}));
axios API
可以通過将相關配置傳遞給 axios 來進行請求。
axios(config)
// 發送一個 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
1
2
// 發送一個 GET 請求 (GET請求是預設請求模式)
axios('/user/12345');
請求方法别名
為了友善起見,已經為所有支援的請求方法提供了别名。
- 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]])
注意
當使用别名方法時,不需要在config中指定url,method和data屬性。
并發
幫助函數處理并發請求。
- 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'}
});
執行個體方法
可用的執行個體方法如下所示。 指定的配置将與執行個體配置合并。
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]])
請求配置
這些是用于送出請求的可用配置選項。 隻有url是必需的。 如果未指定方法,請求将預設為GET。
{
// `url`是将用于請求的伺服器URL
url: '/user',
// `method`是送出請求時使用的請求方法
method: 'get', // 預設
// `baseURL`将被添加到`url`前面,除非`url`是絕對的。
// 可以友善地為 axios 的執行個體設定`baseURL`,以便将相對 URL 傳遞給該執行個體的方法。
baseURL: 'https://some-domain.com/api/',
// `transformRequest`允許在請求資料發送到伺服器之前對其進行更改
// 這隻适用于請求方法'PUT','POST'和'PATCH'
// 數組中的最後一個函數必須傳回一個字元串,一個 ArrayBuffer或一個 Stream
transformRequest: [function (data) {
// 做任何你想要的資料轉換
return data;
}],
// `transformResponse`允許在 then / catch之前對響應資料進行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers`是要發送的自定義 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要與請求一起發送的URL參數
// 必須是純對象或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
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
// `timeout`指定請求逾時之前的毫秒數。
// 如果請求的時間超過'timeout',請求将被中止。
timeout: 1000,
// `withCredentials`訓示是否跨站點通路控制請求
// should be made using credentials
withCredentials: false, // default
// `adapter'允許自定義處理請求,這使得測試更容易。
// 傳回一個promise并提供一個有效的響應(參見[response docs](#response-api))
adapter: function (config) {
/* ... */
},
// `auth'表示應該使用 HTTP 基本認證,并提供憑據。
// 這将設定一個`Authorization'頭,覆寫任何現有的`Authorization'自定義頭,使用`headers`設定。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// “responseType”表示伺服器将響應的資料類型
// 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允許處理上傳的進度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
},
// `onDownloadProgress`允許處理下載下傳的進度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength`定義允許的http響應内容的最大大小
maxContentLength: 2000,
// `validateStatus`定義是否解析或拒絕給定的promise
// HTTP響應狀态碼。如果`validateStatus`傳回`true`(或被設定為`null` promise将被解析;否則,promise将被
// 拒絕。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定義在node.js中要遵循的重定向的最大數量。
// 如果設定為0,則不會遵循重定向。
maxRedirects: 5, // 預設
// `httpAgent`和`httpsAgent`用于定義在node.js中分别執行http和https請求時使用的自定義代理。
// 允許配置類似`keepAlive`的選項,
// 預設情況下不啟用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定義代理伺服器的主機名和端口
// `auth`表示HTTP Basic auth應該用于連接配接到代理,并提供credentials。
// 這将設定一個`Proxy-Authorization` header,覆寫任何使用`headers`設定的現有的`Proxy-Authorization` 自定義 headers。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// “cancelToken”指定可用于取消請求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
使用 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);
});
配置預設值
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';
攔截器
你可以截取請求或響應在被 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);
});
處理錯誤
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 {
//在設定觸發錯誤的請求時發生了錯誤
console.log('Error',error.message);
}}
console.log(error.config);
});
您可以使用validateStatus配置選項定義自定義HTTP狀态碼錯誤範圍。
axios.get('/ user / 12345',{
validateStatus:function(status){
return status < 500; //僅當狀态代碼大于或等于500時拒絕
}}
})
使用application / x-www-form-urlencoded格式
預設情況下,axios将JavaScript對象序列化為JSON。 要以應用程式/ x-www-form-urlencoded格式發送資料,您可以使用以下選項之一。
浏覽器
在浏覽器中,您可以使用URLSearchParams API,如下所示:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
請注意,所有浏覽器都不支援URLSearchParams,但是有一個polyfill可用(確定polyfill全局環境)。
或者,您可以使用qs庫對資料進行編碼:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
檢視更多 請通路我的獨立部落格 https://www.aaz5.com/
關注前端開發 關注使用者體驗
請通路我的新部落格: https://www.cssge.com