axios基础使用

1.axios注意事项

axios的bootcdn标签为
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js"></script>

axios可以用来比较快捷地发ajax。代码示例如下:

1
2
3
4
5
6
7
axios({ //一般写在函数体里面
method: 'POST', //方式
url: 'http://localhost:3000/posts/',
data: { title: '我的题目', author: '张三' } // 仅在post和put里会有的data
}).then(response => {
console.log(response)
})

axios可以设置默认值,可以不再每次都写入method、url等。方法为在像上面调用axios之前写

1
2
axios.default.method = 'GET'
axios.default.url = 'http://www.baidu.com'

btw,如果像这样指定了默认url,想跳转到下面的其他url,就把原来的axios里卖弄的url设定为比如说/posts,也可以达到效果。相当于default确定了基础url。


2.axios拦截器

axios有请求拦截器和响应拦截器。用这个可以脱离用户看见的js对ajax的数据拦截而不被用户篡改。axios中ajax运行顺序为:发出->请求拦截器->服务器->响应拦截器->接收信息。写法如下(要在调用axios之前设置拦截器):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 请求拦截器
axios.interceptors.request.use((config) => {dealWIthConfig()}, (err) => {dealWithError()})
// 响应拦截器
axios.interceptors.response.use((response) => {dealWithResponse()}, (err) => {dealWithErr()})
// 容易看出,上面两个是基于Promise实现的。在err处理的函数中可以return Promise.reject()。当请求拦截器
// 有err,那么下面的响应拦截器也自然会进入err里,下面也会进入catch。
// 在配置好axios后写axios
axios({
method: 'xx',
url: 'xx',
}).then(response => {
dealWithResponse()
}).catch(err => { // 这个catch是当ajax或Promise有异常会进入的分支
dealWithErr()
})


axios可以做到按钮防抖,即取消ajax发送。例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let cancel = null
btn[0].onclick = () => {
if (cancel !== null) {
cancel() // 这里把cancel直接调用,这个写法是固定的,和下面那个token绑定
}
axios({
method: 'xx',
url: 'xx',
cancelToken: new axios.CancelToken(function(c) { // 这个地方设置取消token,写法固定
cancel = c // 将cancel设置非null 从而进入上面的if
})
}).then(response => {
console.log(response)
cancel = null // 整个都请求完了,置null留给下一次使用
})
}