這篇文章主要從下面幾個方面在vue-resource 與axios作了一個比較:
1、安裝
2、全局配置
3、快捷方法和選項配置
4、選項和配置解析
5、基本的http調(diào)用方式
?????全局調(diào)用
?????組件實例調(diào)用
6、respose對象
7、攔截器
8、請求中斷
安裝
- vue-resource
npm install vue-resource --save
cnpm install vue-resource --save(淘寶鏡像安裝)
- axios
npm install axios --save
cnpm install axios --save(淘寶鏡像安裝)
全局配置
- vue-resource
Vue.http.options.root = ' http://sfabric.sm/api/';
Vue.http.headers.common['Accept'] = 'application/json';
Vue.http.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Vue.http.headers.common['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi’
配置了全局默認設置后,在全局和組件的調(diào)用都不用帶頭部
例如:Vue.http.get(url).then()
this.$http.get(url).then()
注意:配置了root后,url需是相對路徑
- axios
Axios.defaults.baseURL = 'http://sfabric.sm/api/';
Axios.defaults.headers.common['Accept'] = 'application/json';
Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Axios.defaults.headers.common['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJh’
配置了全局配置后,在全局和組件的調(diào)用都不用帶頭部
例如:Axios.get(url).then().catch()
this.$http.get(url).then().catch()
注意:配置了baseURL后,url需是相對路徑
快捷方法和選項配置
- vue-resource
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
- axios
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]])
選項和配置解析
- vue-resource options 選項說明
url string 請求的目標URL
body Object, FormData, string 作為請求體發(fā)送的數(shù)據(jù)
headers Object 作為請求頭部發(fā)送的頭部對象
params Object 作為URL參數(shù)的參數(shù)對象
method string HTTP方法 (例如GET,POST,...)
timeout number 請求超時(單位:毫秒) (0表示永不超時)
before function(request) 在請求發(fā)送之前修改請求的回調(diào)函數(shù)
progress function(event) 用于處理上傳進度的回調(diào)函數(shù) ProgressEvent
credentials boolean 是否需要出示用于跨站點請求的憑據(jù)
emulateHTTP boolean 是否需要通過設置X-HTTP-Method-Override頭部并且以傳統(tǒng)POST方式發(fā)送PUT,PATCH和DELETE請求。
emulateJSON boolean 設置請求體的類型為application/x-www-form-urlencoded
- axios config 配置說明
{
// `url`是將用于請求的服務器URL
url: '/user',
// `method`是發(fā)出請求時使用的請求方法
method: 'get', // 默認
// `baseURL`將被添加到`url`前面,除非`url`是絕對的。
// 可以方便地為 axios 的實例設置`baseURL`,以便將相對 URL 傳遞給該實例的方法。
baseURL: 'https://some-domain.com/api/',
// `transformRequest`允許在請求數(shù)據(jù)發(fā)送到服務器之前對其進行更改
// 這只適用于請求方法'PUT','POST'和'PATCH'
// 數(shù)組中的最后一個函數(shù)必須返回一個字符串,一個 ArrayBuffer或一個 Stream
transformRequest: [function (data) {
// 做任何你想要的數(shù)據(jù)轉(zhuǎn)換
return data;
}],
// `transformResponse`允許在 then / catch之前對響應數(shù)據(jù)進行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers`是要發(fā)送的自定義 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要與請求一起發(fā)送的URL參數(shù)
// 必須是純對象或URLSearchParams對象
params: {
ID: 12345
},
// `paramsSerializer`是一個可選的函數(shù),負責序列化`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`是要作為請求主體發(fā)送的數(shù)據(jù)
// 僅適用于請求方法“PUT”,“POST”和“PATCH”
// 當沒有設置`transformRequest`時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
// `timeout`指定請求超時之前的毫秒數(shù)。
// 如果請求的時間超過'timeout',請求將被中止。
timeout: 1000,
// `withCredentials`指示是否跨站點訪問控制請求
// should be made using credentials
withCredentials: false, // default
// `adapter'允許自定義處理請求,這使得測試更容易。
// 返回一個promise并提供一個有效的響應(參見[response docs](#response-api))
adapter: function (config) {
/* ... */
},
// `auth'表示應該使用 HTTP 基本認證,并提供憑據(jù)。
// 這將設置一個`Authorization'頭,覆蓋任何現(xiàn)有的`Authorization'自定義頭,使用`headers`設置。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// “responseType”表示服務器將響應的數(shù)據(jù)類型
// 包括 '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響應內(nèi)容的最大大小
maxContentLength: 2000,
// `validateStatus`定義是否解析或拒絕給定的promise
// HTTP響應狀態(tài)碼。如果`validateStatus`返回`true`(或被設置為`null` promise將被解析;否則,promise將被
// 拒絕。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定義在node.js中要遵循的重定向的最大數(shù)量。
// 如果設置為0,則不會遵循重定向。
maxRedirects: 5, // 默認
// `httpAgent`和`httpsAgent`用于定義在node.js中分別執(zhí)行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`設置的現(xiàn)有的`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) {
})
}
基本的http調(diào)用方式
全局調(diào)用
- vue-resource
vue-resource 在全局調(diào)用直接使用:
get方法 get(url,[options])
Vue.http.get(url).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
},function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
post方法post(url,[body],[options])
Vue.http.post(url,orderObj).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
},function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
put方法put(url,[body],[options])
Vue.http.put(url,orderObj).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
},function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
delete方法 delete(url,[options])
Vue.http.delete(url).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
},function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
- axios
先在全局引入Axios:
import Axios from ‘a(chǎn)xios’
引入后再調(diào)用:
get方法 get(url [,config])
Axios.get(url).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
}).catch(function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
post方法 post(url [,data [,config]])
Axios.post(url,orderObj).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
}).catch(function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
put方法 put(url [,data [,config]])
Axios.put(url,orderObj).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
}).catch(function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
delete方法 delete(url [,config])
Axios.delete(url).then(function(response){
console.log(“成功的回調(diào)函數(shù)”)
}).catch(function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
組件實例調(diào)用
- vue-resource
this.$http.get(url).then(
function(response){
console.log(“成功的回調(diào)函數(shù)”)
},function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
- axios
this.$http.get(url).then(
function(response){
console.log(“成功的回調(diào)函數(shù)”)
}).catch(function(error){
console.log(“失敗的回調(diào)函數(shù)”)
})
respose對象
- vue-resource response對象數(shù)據(jù)格式
1. body:
1. data:(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2. message:"請求成功!"
3. moneysum:(2) [{…}, {…}]
4. quantitysum:[{…}]
5. total:107
6. __proto__:Object
2. bodyText:"{"message":"\u8bf7\u6c42\u6210\u529f\uff01","total":107,"moneysum":[{"cur_code":"\u00a5 ","money":127381}"
3. headers:Headers
1. map:{content-type: Array(1), cache-control: Array(1)}
2. __proto__:Object
4. ok:true
5. status:200
6. statusText:"OK"
7. url:"http://sfabric.sm/api/sales-order?page=1&per_page=10&type=1,2"
8. data:Object
1. data:(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2. message:"請求成功!"
3. moneysum:(2) [{…}, {…}]
4. quantitysum:[{…}]
5. total:107
- axios response 對象數(shù)據(jù)格式
1. config:
1. adapter:? xhrAdapter(config)
2. baseURL:"http://sfabric.sm/api/"
3. data:undefined
4. headers:{Accept: "application/json", X-Requested-With: "XMLHttpRequest", Authorization: "Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI…
dU12fxHarJv04UqlHahapT3vp4hWNXos_h2TQqzDyRfcQxOWY"}
5. maxContentLength:-1
6. method:"get"
7. timeout:0
8. transformRequest:{0: ?}
9. transformResponse:{0: ?}
10. url:"http://sfabric.sm/api/sales-order?page=1&per_page=10&type=1,2"
11. validateStatus:? validateStatus(status)
12. xsrfCookieName:"XSRF-TOKEN"
13. xsrfHeaderName:"X-XSRF-TOKEN"
14. __proto__:Object
2. data:{message: "請求成功!", total: 107, moneysum: Array(2), quantitysum: Array(1), data: Array(10)}
3. headers:{content-type: "application/json", cache-control: "no-cache"}
4. request:XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ?, …}
5. status:200
6. statusText:"OK"
攔截器
- vue-resource
//請求的處理
Vue.http.interceptors.push(function(request, next) {
// modify method
request.method = 'POST';
// modify headers
request.headers.set('X-CSRF-TOKEN', 'TOKEN');
request.headers.set('Authorization', 'Bearer TOKEN');
// continue to next interceptor
next();
});
//請求和響應的處理
Vue.http.interceptors.push(function(request, next) {
// modify request
request.method = 'POST';
// continue to next interceptor
next(function(response) {
// modify response
response.body = '...';
});
});
//返回一個響應并停止處理(?)
Vue.http.interceptors.push(function(request, next) {
// modify request ...
// stop and return response
next(request.respondWith(body, {
status: 404,
statusText: 'Not found'
}));
});
攔截器的使用,方便統(tǒng)一處理請求加頭部,登錄錯誤處理,響應錯誤處理 ,顯示異步加載狀態(tài)
- axios
//請求攔截處理
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// 響應攔截處理
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
請求中斷
- vue-resource
{
// GET /someUrl
this.$http.get('/someUrl', {
// use before callback
before(request) {
// abort previous request, if exists
if (this.previousRequest) {
this.previousRequest.abort();
}
// set previous request on Vue instance
this.previousRequest = request;
}
}).then(response => {
// success callback
}, response => {
// error callback
});
}
- axios
你可以通過cancel token來取消一個請求
使用CancelToken.source的工廠函數(shù)來創(chuàng)建一個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 {
// handle error
}
});
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
你也可以通過CancelToken的構(gòu)造函數(shù)執(zhí)行器來創(chuàng)建一個cancel token
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();