基本概念
这是一个处理异步请求的插件。
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
methods string 请求的HTTP方法
body POST请求时带的参数(request body)
params Object GET请求时的URL参数
headers Object 请求第三方时的请求头部参数(request header)
timeout number 单位为毫秒的请求超时时间,超过接口就会终止
before function(request) 请求发送前的处理函数
progress function(event) 回调处理函数,例如做进度
credientials boolean 表示跨域时,是否需要使用凭证
emulateHTTP boolean 发送PUT、PATCH、DELETE请求时,以POST的方式发送
在请求头设置 X-HTTP-Method-Override
emulateJSON boolean 将request body以 application/x-www-form-urlencoded content type 发送
全局拦截器 interceptors
语法
Vue.http.interceptors.push((request,next) => {
//...
//请求发送前的处理逻辑
//...
next((response) => {
//...
//请求发送后的处理逻辑
//...
//根据请求状态,response参数返回给successCallback或errorCallback
return response
})
})
DEMO演示
Get请求
get(){
//使用this.$http发送请求
this.$http.get("package.json",{
//传参
params: {
userId: "101"
},
headers:{
//往请求头部注入token
token: "abcd"
}
})
//请求成功后捕获 res等于success
.then(res =>{
this.msg = res.data;
},
error =>{
this.msg = error;
});
}
Post请求
post(){
this.$http.post("package.json",{
//直接写要传的参数
userId: "102"
},
{
//这里写请求配置
headers:{
//往请求头部注入access_token
access_token: "abc"
}
})
.then(res =>{
this.msg = res.data;
},error => {
this.mag = error;
});
}
JSONP请求
jsonp(){
//这里是参数 这里是默认要设置的
this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'a'},{jsonp:'callback'})
.then(res =>{
this.msg = res.data;
},error => {
this.mag = error;
});
}
全局拦截器的使用
在mounted里面定义
mounted: function(){
Vue.http.interceptors.push(function(request,next){
console.log("请求发送前");
//next是请求后,响应完了
next(function(res){
console.log("响应了");
return res;
});
});
},
//这下面是设置根路径
http:{
root:"http://localhost:63342/vue/ImoocMall/"
}