axios基础api

axios

基于http客户端的promise,面向浏览器和nodejs

特色

  • 浏览器端发起XMLHttpRequests请求

  • node端发起http请求

  • 支持Promise API

  • 监听请求和返回

  • 转化请求和返回

  • 取消请求

  • 自动转化json数据

  • 客户端支持抵御

安装

//使用npm:
$ npm i axiso
使用 bower
$ bower instal axios
//使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

示例

使用一个 GET 请求

//发起一个user请求,参数为给定的ID
axios.get('/user?ID=1234')
.then(function(respone){
    console.log(response);
})
.catch(function(error){
    console.log(error);
});

//上面的请求也可选择下面的方式来写
axios.get('/user',{
    params:{
        ID:12345
    }
})
    .then(function(response){
        console.log(response);
    })
    .catch(function(error){
        console.log(error)
    });

发起一个 POST 请求

axios.post('/user',{
    firstName:'friend',
    lastName:'Flintstone'
})
.then(function(response){
    console.log(response);
})
.catch(function(error){
    console.log(error);
});

发起一个多重并发请求

function getUserAccount(){
    return axios.get('/user/12345');
}

function getUserPermissions(){
    return axios.get('/user/12345/permissions');
}

axios.all([getUerAccount(),getUserPermissions()])
    .then(axios.spread(function(acc,pers){
        //两个请求现在都完成
    }));

axios API

axios 能够在进行请求时进行一些设置。

axios(config)

//发起 POST请求

axios({
    method:'post',
    url:'/user/12345',
    data:{
        firstName:'Fred',
        lastName:'Flintstone'
    }
});

axios(url[,config])

//发起一个GET请求
axios('/user/12345/);

请求方法的重命名。

为了方便,axios提供了所有请求方法的重命名支持

axios.request(config)

axios.get(url[,config])

axios.delete(url[,config])

axios.head(url[,config])

axios.post(url[,data[,config]])

axios.put(url[,data[,config]])

axios.patch(url[,data[,config]])

注意

当时用重命名方法时 url , method ,以及 data 特性不需要在config中设置。


猜你喜欢

转载自blog.csdn.net/weixin_39460408/article/details/80520109
今日推荐