axios的基本使用

1 axios的基本使用

1.1 使用默认方式发送无参请求

<script>
axios({url:'http://...../xxx'}).then(res=>{})
</script>

1.2. 使用get方式请求

<script>
    //无参
axios({url:'http://...../xxx'}).then(res=>{})
    //有参
axios({url:'http://...../xxx?id=1'}).then(res=>{})   
    //传对象
axios({url:'http://...../xxx?id=1',params:{id:'1',name:'xxx'}}).then(res=>{})       
</script>

1.3 使用post方式请求

axios({
    url:'http://...../xxx?id=1',
    method:'post',
    params:{id:'1',name:'xxx'
}}).then(res=>{}) 

后台控制器接收到的name 为null

原因是:axios使用post携带参数请求默认使用application/json

解决方式一:params属性进行数据的传递
解决方式二:直接写"name=张三"
解决方式三:服务器段给接收到的参数加上@requestBody

2 axios请求方式

2.1 使用axios.get方式

无参

axios.get('http://...../xxx').then(res=>{
}).catch(err=>{    
})

有参

axios.get('http://...../xxx',{params:{id:1,name:xxx}}).then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)
})

2.2 使用axios.post方式

无参

axios.post('http://...../xxx').then(res=>{
     console.log(res)
}).catch(err=>{
    console.log(err)
})

有参

axios.post('http://...../xxx',"name=张三&age=10").then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)
})

使用data传递数据,后台需要将axios 自动转换的 json数据 转换为java对象

要修改后台代码(接收参数添加@requestBody注解)

axios.post('http://...../xxx',{id:1,name:xxx}).then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)
})

3 axios发送并发请求

axios.all().then().catch()
axios.all(
    [
        axios.get('http:/xxxxxx/xxxx'),
        axios.get('http:/xxxxxx/xxxx',{params:{id:1}}),
    ]).then(res=>{//请求成功返回的是一个数组
        console.log(res)
        console.log(res[0])
        console.log(res[1])
    }
    ).catch(err=>{
        console.log(err)
    })

将响应数据自动分离

axios.spread((res1,res2)=>{
    console.log(res1);
    console.log(res2);
})

4 axios全局配置

<script>
    axios.default.baseURL = 'http:/xxxx:8080';//基础路径
    axios.default.timeout = 5000;//超时时间
    //自动拼接baseURL
   
</script>

5 axios的实例

请求拦截器(成功、失败)。use两个函数作为参数

<script>
    //创建axios的实例
    let service = axios.create({
        baseURL:'http://xxxx:9999',
        temout:5000
    })
    let service2 = axios.create({
        baseURL:'http://xxxx:9999',
        temout:5000
    })
        

    service({
        url:'getxxx'
    }).then(res=>{
        console.log(res);
    })

</script>

6 axios拦截器

axios.interceptors.request.use(config=>{
    console.log("进入请求拦截器")
    return config;//放行请求 *
    //config包含data、headers、request、status、statusText
},err=>{
    console.log("请求失败")
})

响应拦截器(成功、失败)

axios.interceptors.response.use(config=>{
    console.log("响应拦截器")
    
    return config;//放行
},err=>{
    console.log("响应失败")
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容