在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/

