axios

安装

先在当前项目安装axios

cnpm i axios -S

 

get请求

axios.get('http://localhost:8082/getAllStudents').then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});

上面这个例子并没有带参数过去,如果需要携带参数可以有2种写法。

方法1

直接在请求的地址里,写上?key=value

axios.get('http://localhost:8082/getStudentsByName?name=marry').then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});

方法2

axios.get('http://localhost:8082/getStudentsByName', {
    params : {
        name : 'tom'
    }
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});

 

post请求

post请求与get请求类似,不同的是,如果post请求需要携带参数过去给服务器,需要把参数转换成key=value&key=value这种形式。

axios.post('http://localhost:8082/getStudentsByName', qs.stringify({
    name : 'tom'
})).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});

这里的qs.stringify是笔者写的一个方法而已,代码如下 :

var qs = {
    stringify(json){
        Object.keys(json).forEach(key => {
            !json[key] && delete json[key];
        });
        let queryStr = Object.keys(json)
            .map(key => {
            return `${key}=${json[key]}`;
            }).join("&");
        
        return queryStr;
    }
}

该方法会把json对象转换成key=value&key=value这种形式。

 

并发请求

axios提供all方法,可以等待所有请求都完成后,统一处理。如 :

function getAllStudents(){
    return axios.get('http://localhost:8082/getAllStudents');
}

function getStudentsByName(){
    return axios.get('http://localhost:8082/getStudentsByName?name=marry');
}

axios.all([getAllStudents(), getStudentsByName()])
.then(function(res){
    console.log(res);
});

这里的res返回的是一个数组

如果我们要对数据进行过操作,则需要res[0]、res[1]这样操作,不太方便。这里可以使用axios提供的spread方法,如下 :

function getAllStudents(){
    return axios.get('http://localhost:8082/getAllStudents');
}
function getStudentsByName(){
    return axios.get('http://localhost:8082/getStudentsByName?name=marry');
}

axios.all([getAllStudents(), getStudentsByName()])
.then(axios.spread(function(res1,res2){
    console.log(res1);
    console.log(res2);
}));

打印结果:

 

使用实例来请求

在一个项目中,请求的地址不可能都是同一个url,总会有一两个接口是别的域名。这时候我们可以创建单独的axios实例来为这个接口做请求。如 :

let newVar = axios.create({
    baseURL : 'http://localhost:8082', //请求的ip
    timeout : 5000 //超时时间设置
});

newVar({
    url : 'getAllStudents'
}).then(res=>{
    console.log(res);
});

调用create方法来创建一个实例

 

全局配置

我们上面的例子,在请求一个ip的时候,都需要写全 :

下面通过axios的全局配置,来达到不需要写全。代码 :

axios.defaults.baseURL = 'http://localhost:8082'; //设置请求的ip
axios.defaults.timeout = 5000; //设置请求超时时间

axios.get('/getAllStudents').then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
});

axios的全局配置还不止这2个,更多全局配置请查看官方文档。

 

拦截器

axios提供的拦截器有2个,一个是请求之前,一个是请求之后。例子 :

比如我们上面的post请求,我们需要用qs.stringify来转换数据,一个项目大大小小可能会有上百个请求,哪天axios更新了,可以使用json来传递数据给服务器,这时我们需要修改的话就太浪费时间了。

所以我们可以在请求之前,判断这个请求是不是post请求,如果是,则把他的json数据转换成key=value的这种形式。这个判断可以写在axios的拦截器的请求之前。如下 :

//添加请求拦截器
axios.interceptors.request.use(function (config) {  
    //判断请求是不是post请求
    if(config.method === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

//添加响应拦截器
axios.interceptors.response.use(function (response) {
    console.log(response);
    return response;
}, function (error) {
    return Promise.reject(error);
});

axios.post('http://localhost:8082/getStudentsByName2', {   //这里直接传入json即可
    name : 'tom'
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
})

其中,axios.interceptors.request.use里面的config,打印出来是这么一个内容 :

而axios.interceptors.response.use的response是这么一个内容 :

实际上就是和我们接受到服务器返回来的数据是同一个东西。所以拦截器的作用实际上就是请求前,我们可以提前对数据进行一些操作,请求后我们也可以对返回的数据进行统一的判断。例如状态码,你一定这么写过 :

if(res.status == 1004){
    alert('服务器繁忙,请喝杯茶休息一会儿');
}else if(res.status == 1005){
    alert('网络错误');
}
//都没错了,在进行下面的代码处理

如果每个请求都需要重新写一遍,那不累死。所以这个判断可以放在axios.interceptors.response.use去判断。

如 :

axios.interceptors.response.use(function (response) {
    if(response.status == 1004){
        alert('服务器繁忙,请喝杯茶休息一会儿');
        break;
    }else if(response.status == 1005){
        alert('网络错误');
        break;
    }
    return response;
}, function (error) {
    return Promise.reject(error);
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值