异步请求vue-resource与axios用法的详细比较

安装

1
2
3
4
5
6
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.get(url).then()
this.$http.get(url).then()
注意:配置了root后,url需是相对路径

1
2
3
4
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'

axios

配置了全局配置后,在全局和组件的调用都不用带头部
例如:Axios.get(url).then().catch()
this.$http.get(url).then().catch()
注意:配置了baseURL后,url需是相对路径

1
2
3
4
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’

快捷方法和选项配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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 选项说明

1
2
3
4
5
6
7
8
9
10
11
url     string  请求的目标URL
body Object, FormData, string 作为请求体发送的数据
headers Object 作为请求头部发送的头部对象
params Object 作为URL参数的参数对象
method string HTTP方法 (例如GET,POST,...)
timeout number 请求超时(单位:毫秒) (0表示永不超时)
before function(request) 在请求发送之前修改请求的回调函数
progress function(event) 用于处理上传进度的回调函数 ProgressEvent
credentials boolean 是否需要出示用于跨站点请求的凭据
emulateHTTP boolean 是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUT,PATCH和DELETE请求。
emulateJSON boolean 设置请求体的类型为application/x-www-form-urlencoded

axios config 配置说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
{
// `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) {
})
}

基本的http调用方式

全局调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// vue-resource
//vue-resource 在全局调用直接使用:
get方法 get(url,[options])
Vue.http.get(url).then(function(response){
console.log(“成功的回调函数”)
},function(error){
console.log(“失败的回调函数”)
})

post方法post(url,[body],[options])
Vue.http.post(url,orderObj).then(function(response){
console.log(“成功的回调函数”)
},function(error){
console.log(“失败的回调函数”)
})

put方法put(url,[body],[options])
Vue.http.put(url,orderObj).then(function(response){
console.log(“成功的回调函数”)
},function(error){
console.log(“失败的回调函数”)
})

delete方法 delete(url,[options])
Vue.http.delete(url).then(function(response){
console.log(“成功的回调函数”)
},function(error){
console.log(“失败的回调函数”)
})


// axios 先在全局引入Axios:
//import Axios from ‘axios’
get方法 get(url [,config])
Axios.get(url).then(function(response){
console.log(“成功的回调函数”)
}).catch(function(error){
console.log(“失败的回调函数”)
})

post方法 post(url [,data [,config]])
Axios.post(url,orderObj).then(function(response){
console.log(“成功的回调函数”)
}).catch(function(error){
console.log(“失败的回调函数”)
})

put方法 put(url [,data [,config]])
Axios.put(url,orderObj).then(function(response){
console.log(“成功的回调函数”)
}).catch(function(error){
console.log(“失败的回调函数”)
})

delete方法 delete(url [,config])
Axios.delete(url).then(function(response){
console.log(“成功的回调函数”)
}).catch(function(error){
console.log(“失败的回调函数”)
})

组件实例调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// vue-resource
this.$http.get(url).then(
function(response){
console.log(“成功的回调函数”)
},function(error){
console.log(“失败的回调函数”)
})

// axios
this.$http.get(url).then(
function(response){
console.log(“成功的回调函数”)
}).catch(function(error){
console.log(“失败的回调函数”)
})

respose对象

vue-resource response对象数据格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// vue-resource response对象数据格式
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 对象数据格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//请求的处理
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'
}));
});

拦截器的使用,方便统一处理请求加头部,登录错误处理,响应错误处理 ,显示异步加载状态

axios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//请求拦截处理
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
你可以通过cancel token来取消一个请求
使用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 {
// handle error
}
});

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

你也可以通过CancelToken的构造函数执行器来创建一个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();
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!