Vue-resource和Axios

我们先讲vue-resource,vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:

  • get( url, [options] )
  • head( url, [options] )
  • delete( url, [options] )
  • jsonp( url, [options])
  • post( url, [body], [options])
  • put( url, [body], [options])
  • patch( url, [body], [options])
参数 类型 描述
url string 请求的URL
method string 请求的HTTP方法,例如:'GET'或其他HTTP方法
body Object,FormDatastring request body
params Object 请求的URL参数对象
headers Object request header
timeout number 单位为毫秒的请求超时时间(0表示无超时时间)
before function(request) 请求发送前的处理函数,类似于jQuery的beforeSend函数
progress function(event) ProgressEvent回调处理函数
credientials boolean 表示跨域请求时是否需要凭证
emulateHTTP boolean 发送PUT,PATCH,DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override

全局拦截器interceptors:

Vue.http.interceptors.push((request,next)=>{
    //...
    //请求发送前的处理逻辑
    //...
  next((response)=>{
    //...
    //请求发送后的处理逻辑
    //...
    //根据请求的状态,response参数会返回给sucessCallback或errorCallback
    return response
  })
})

get请求:     post请求:

jsonp请求:

拦截器:

地址全局配置:

另一种配置方式:

http:function(){
    this.$http({
        url:"package.json",
        method:"get",
        params:{
            userId:"101"
        },
        headers:{
            token:"102"
        },
        timeout:5,
        before: function(){
            console.log("before init")
        },
    }).then(function(res){
        this.msg=res.data;
    })
}

接下来我们来看一下Axios的API:

  • 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])

get请求:   post请求:

另一种配置方式:发送get请求就要在params里面定义,post就在data里面定义

Axios的全局拦截器配置:

猜你喜欢

转载自blog.csdn.net/stormzi/article/details/90369764