本文只是初级介绍axios最基本用法(get,post,all请求),至于扩展和延伸只是没有过多赘述,更多内容可以参看axios官网。如有不周之处还请谅解。
个人建议使用npm安装开始项目(进入到相关命令行工具中操作即可)
使用npm:
$ npm i axios
tip:
react在引进axios时所用 '' 实际为 `` 即反引号!好处就是不用拼接字符串``,遇到变量就是${}就可以了。
示例一
使用一个 GET
请求
//发起一个login请求,参数为给定的ID
axios.get('/login?ID=12345')
.then(function(res){
console.log(res);
})
.catch(function(error){
console.log(error);
});
//上面的请求也可选择以下面的方式来改写
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(res){
console.log(res);
})
.catch(function(error){
console.log(error)
});
下面是我自己在项目里面常用的写法,个人觉得不错,贡献出来......
例如:
let idid=this.props.ID
let timestamp = Date.parse(new Date());
axios.get(`${url}/invoice/GetListNoGroup?id=${idid}&×tamp=${timestamp}`)
.then(res=>{console.log(res.data)})
.catch(err=>console.log(err))
示例二
发起一个 POST
请求
axios.post('/reg',{
Name:'hopefullman',
pass:'123456'
})
.then(function(res){
console.log(res);
})
.catch(function(error){
console.log(error);
});
下面是我自己在项目里面常用的写法,个人觉得不错,贡献出来......
例如:
let data={
name:admin,
password:password,
}
axios.post(`${url}/UserInfo/Login`,data)
.then(res=>this.loginok(res))
.catch(err=>this.loginerr(err))
示例三
发起一个多重并发请求
function getUser(){
return axios.get('/login/12345');
}
function getAccount(){
return axios.get('/reg/12345');
}
axios.all([getUer(),getAccount()])
.then(axios.spread(function(acc,pers){
}));
来来来补充下关于验证服务器的一些办法:
来一个类似原生的:
axios.post("http://gst.bclzdd.com/connect/token","client_id=client2&client_secret=secret&username="+username+"&password="+password+"&grant_type=password")
.then(res=>{console.log(res)})
.catch(err=>{console.log(err)})
来一个axios的 axios.post(`${url}/connect/token`,`client_id=client2&client_secret=secret&username=${username}&password=${password}&grant_type=password`)
.then(res=>{console.log(res)})
.catch(err=>{console.log(err)})
来一个formdata形式:
axios.post(`${configUrl}/User/edit_password`,`userId=${userId}&token=${token}&oldPwd=${oldPwd}&password=${password}&passwords=${passwords}`)
.then((res)=>{
let strperson=eval('(' + res.data + ')');
this.refs.toast.show(strperson.info);
})
.catch((err)=>{
console.log(err);
})
来一个json形式:
let userId=this.props.userId;
let token=this.props.token;
let oldPwd=this.state.oldpassword;
let password=this.state.password;
let passwords=this.state.passwords;
axios.post(`${configUrl}/User/edit_password`,data)
.then((res)=>{
let strperson=eval('(' + res.data + ')');
this.refs.toast.show(strperson.info);
})
.catch((err)=>{
console.log(err);
})