- 基础使用
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
<script>axios.get('https://study.duyiedu.com/api/herolist').then(res=> {console.log(res.data)})
</script>
- get - params
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
<script>axios.get('https://study.duyiedu.com/api/herolist', {params: {// 这里配置的 query, axios 会自动配置为 url 编码// 可以帮助我们转义特殊字符 id: 'a&b=3' 如果手动写query 需要id: 'aaa' // https://study.duyiedu.com/api/herolist?id=aaa}}).then(res=> {console.log(res.data)})
</script>
id: 'a&b=3' // https://study.duyiedu.com/api/herolist?id=a%26b%3D3
- post
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
<script>axios.post('https://study.duyiedu.com/api/user/reg', {// {"loginId":"aaa","loginPwd":"123123","nickname":"棒棒鸡"} 自动转为 JSON 格式和对应的请求头loginId: 'aaa',loginPwd: '123123',nickname: '棒棒鸡'}).then(res => {console.log(res.data) // res.data 为响应体数据 axios 会自动解析为 JSON 格式})
</script>
- 创建实例
const instance = axios.create({baseURL: 'https://study.duyiedu.com/api',timeout: 1000,
});
create 创建 axios 实例,预先配置某些配置项,减少重复代码。
- 拦截器
【Ajax】axios 二次封装请求响应拦截器_ajax响应拦截器-CSDN博客