vue学习第22天,axios插件

来源:互联网 发布:足球球员数据网站 编辑:程序博客网 时间:2024/05/18 02:01

1,npm install axios --save 安装 axios 

2,通过 node_modules/axios/dist/axios.js 引用

3,常用 get post http 

4,拦截器 在发请求的前后 进行一些校验

5,vue-resource 的拦截器 

mounted:function(){

Vue.http.interceptors.push(function(request,next){

console.log("请求之前打印");

next(function(resource){

console.log("拿到响应后打印")

return response;

})

})

}

6,vue-resource 的 http 请求

http:function(){

this.$http({

url:'目标路径',

params:{

userId:"传递的参数"

},

headers:{

token:"可以在请求头里面塞第三方需要的一些参数"

},

timeout:5,//请求超时时间

before:function(){}

}).then((res)=>{

this.msg=res.data

},(error)=>{

this.msg=error

})

}

7,axios 插件的拦截器

mounted:function(){

axios.interceptors.request.use((config)=>{

console.log('请求之前拦截')

return config;

}),

axios.interceptors.response.use((response)=>{

console.log('拿到响应之后拦截');

return response;

})

}

8,axios 插件主要常用 get post http

get:function(){

axios.get('目标路径',{

params:{

userId:"传递参数"

},

headers:{

token:"在请求头里边赛第三方需要的参数"

}

}).then(res=>{

this.msg=res.data;

}).catch(error=>{

this.msg=error

})

}

post:function(){

axios.post('目标路径',{

params:{

userId:"传递参数"

},

headers:{

token:"在请求头里边塞入第三方要的参数"

}

}).then(res=>{

this.msg=res.data;

}).catch(erroe=>{

this.msg=error;

})

}

http:function(){

axios({

url:"路径",

method:"post",//类型

data:{

userId:"传递参数"

},

headers:{

token:"在请求头里边塞入第三方需要的参数"

}

}).then(res=>{

this.msg=res.data;

}).catch(error=>{

this.msg=error;

})

}