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

这篇文章主要从下面几个方面在vue-resource 与axios作了一个比较:
1、安装
2、全局配置
3、快捷方法和选项配置
4、选项和配置解析
5、基本的http调用方式
     全局调用
     组件实例调用
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’

配置了全局默认设置后,在全局和组件的调用都不用带头部
例如: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’

配置了全局配置后,在全局和组件的调用都不用带头部
例如: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    作为请求体发送的数据
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 配置说明
{
  // `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调用方式

全局调用
  • 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(“失败的回调函数”)
})
组件实例调用
  • 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.  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.  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'
  }));
});

拦截器的使用,方便统一处理请求加头部,登录错误处理,响应错误处理 ,显示异步加载状态
  • 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的工厂函数来创建一个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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 乐乐_36c5阅读 157评论 0 0
  • 一、 ARC环境 单个viewController的生命周期initWithCoder:(NSCoder *)aD...
    Mitchell阅读 37,474评论 5 64
  • 跑马溜溜的山上 一朵溜溜的云哟 端端溜溜的照在 康定溜溜的城哟 月亮弯弯 康定溜溜的城哟 ...
    恰克Linton阅读 404评论 0 0
  • 五月, 阳光透过繁密的枝叶, 洒下斑驳的光影。 那光影,像是时光的罅隙, 那些过往的淡淡的 甜蜜的美丽的 忧伤的惆...
    情浓休说痴阅读 305评论 4 10