使用axios上传数据(包括其中的一些坑)

axios,是有一个基于es6中的promise开发的一个http库,他的主要功能就是向服务端请求和发送数据,promise可以简单的理解为只有三种状态,即pending(进行)->fulfiled(成功)和pending(进行)->rejected(失败)。
因此,我们在调用完成之后,在末尾总是需要加上then()和catch(),他们分别表示成功和失败之后所做的动作。
与jquery中的ajax不同的是,axios的get请求在附带参数发送的时候,需要带上一个params对象。因此,总结如下:
get请求:
axios.get('url',{
    params:{
        data:data  即所需要上传的参数
    }
}).then((response)=>{

}).catch((error)=>{

})

post请求(和jquery的ajax相差不大,无非最明显的就是继承的promise) :
axios.post('url',{
    data:data  即所需要上传的参数 
}).then((response)=>{

}).catch((error)=>{

})

axios也可以通过传递相关配置来创建http请求:
axios({
    method:'',
    url:'',
    data:{},
})

axios还支持多个并发请求(用all方法):

getUserAccount(){
    return axios.get('url');
}

getUserPassword(){
    return axios.get('url');
}

axios.all([getUserAccount(),getUserPassword]).then(axios.spread((acct,perms)=>{
    //两个请求现在都已执行完毕
}))

猜你喜欢

转载自blog.csdn.net/qq_36529459/article/details/80255777
今日推荐