vue axios数据请求及vue中使用axios的方法
axios简介
axios是一个基于Promise用于浏览器和nodejs的HTTP客户端,它本身具有以下特征:
--------------------------------------------------------------------------------
•从浏览器中创建XMLHttpRequest
•从node.js发出http请求
•支持PromiseAPI
•拦截请求和响应
•转换请求和响应数据
•取消请求
•自动转换JSON数据
•客户端支持防止CSRF/XSRF
在vue中数据请求需要先安装axios
npmi--saveaxios
我们在使用请求数据的页面导入axios
import axiosfrom"axios"
然后在methods里面写数据的请求
methods:{
getInfo(){
leturl="url"
axios.get(url).then((res)=>{
//console.log(res)
this.list1=res
})
}
在生命周期调用一下,一般我们数据请求使用的生命周期是Mounted
mounted(){
this.getInfo()
}
这样我们就完成了axios的get方法请求
然后我们简答的说一说post请求,post请求与get请求其实变得不多
postInfo(){
leturl="..."
varparams=newURLSearchParams();
params.append('key',index);
axios.post(url,params).then((res)=>{
console.log(res)
})
}
这样我们就可以成功的使用post方法请求数据了
补充:下面看下vue中使用axios
1.安装axios
npm:
$npminstallaxios-S
cdn:
2.配置axios
在项目中新建api/index.js文件,用以配置axios
api/index.js
importaxiosfrom'axios';
lethttp=axios.create({
baseURL:'http://localhost:8080/',
withCredentials:true,
headers:{
'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest:[function(data){
letnewData='';
for(letkindata){
if(data.hasOwnProperty(k)===true){
newData+=encodeURIComponent(k)+'='+encodeURIComponent(data[k])+'&';
}
}
returnnewData;
}]
});
functionapiAxios(method,url,params,response){
http({
method:method,
url:url,
data:method==='POST'||method==='PUT'?params:null,
params:method==='GET'||method==='DELETE'?params:null,
}).then(function(res){
response(res);
}).catch(function(err){
response(err);
})
}
exportdefault{
get:function(url,params,response){
returnapiAxios('GET',url,params,response)
},
post:function(url,params,response){
returnapiAxios('POST',url,params,response)
},
put:function(url,params,response){
returnapiAxios('PUT',url,params,response)
},
delete:function(url,params,response){
returnapiAxios('DELETE',url,params,response)
}
}
这里的配置了POST、GET、PUT、DELETE方法。并且自动将JSON格式数据转为URL拼接的方式
同时配置了跨域,不需要的话将withCredentials设置为false即可
并且设置了默认头部地址为:http://localhost:8080/,这样调用的时候只需写访问方法即可
3.使用axios
注:PUT请求默认会发送两次请求,第一次预检请求不含参数,所以后端不能对PUT请求地址做参数限制
首先在main.js中引入方法
importApifrom'./api/index.js'; Vue.prototype.$api=Api;
然后在需要的地方调用即可
this.$api.post('user/login.do(地址)',{
"参数名":"参数值"
},response=>{
if(response.status>=200&&response.status<300){
console.log(response.data);\\请求成功,response为成功信息参数
}else{
console.log(response.message);\\请求失败,response为失败信息
}
});