axios二次封装
axios是什么?github库上给出了一段解释:Promise based HTTP client for the browser and node.js。对于一名使用过react/vue的前端开发者来说对其并不会陌生。下面是一段十分常见的axios代码
axios({
method: 'get',
headers: { 'Authorization': SessionStorage.get('token') },
url: `http://127.0.0.1:3000/test`,
params: obj
}).then(result => {
if(result.data.code){
console.log('操作成功')
} else {
console.log(result.data.msg)
}
})
可以看出axios大大的方便了前端开发拿去请求数据,但是这样的写法也存在几个问题。1.每次请求都会都会设置baseurl(http://127.0.0.1:3000)。2.每次都会去sessionstorage中取token然后放在headers中。3.还有一个问题就是axios的重复点击问题。
准备(查看文档)
- baseURL设置
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})
查看文档可知,使用axios.create()可以得到axios的一个实例,而通过config可以配置baseURL以及一些其他配置(其他配置我就没研究,到时候需要的时候在研究吧~)
- token设置
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
- 重复点击cancelToken
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
有必要说一下重复点击是什么?eg:如果一个按钮是向后台发起请求并且获取数据,如果数据量大或者网络的一些原因,就会导致用户点击下一次的时候上一次还没有完成,就发起了两次请求,页面可能就会render两次。所以cancelToken的目的就是将上一次置为cancel。
封装
使用class进行封装
class Http {
constructor() {
// 获取axios实例并且设置baseURL
this.http = axios.create({baseURL: address})
// cancel设置
this.cancel = f => f
this.cancelToken = new axios.CancelToken(cancel => {this.cancel = cancel})
}
setToken() {
// 获取token并且设置token
let token = sessionStorage.getItem('token')
if(token) this.http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
}
各类型封装
post = (url, data = {}) => {
// 每次请求之前先设置token
this.setToken()
return this.http({
method: 'post',
data: data,
url: url,
// 防止重复点击
cancelToken: this.cancelToken
})
}
返回的是一个Promise对象
使用
import axios from 'tooles/http'
axios.post(`/user/login`, data)
.then(result => {
console.log('进行操作')
})
完整代码
/**
* axios请求二次封装
* 设置了baseURL
* 设置了token
* 避免重复点击
*/
import {address} from 'config'
import axios from 'axios'
class Http {
constructor(){
this.http = axios.create({baseURL: address})
this.cancel = f => f
this.cancelToken = new axios.CancelToken(cancel => {this.cancel = cancel})
}
setToken() {
let token = sessionStorage.getItem('token')
if(token) this.http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
getHttp = () => {
return this.http
}
get = (url, params = {}) => {
this.setToken()
return this.http({
method: 'get',
params: params,
url: url,
cancelToken: this.cancelToken
})
}
post = (url, data = {}) => {
this.setToken()
return this.http({
method: 'post',
data: data,
url: url,
cancelToken: this.cancelToken
})
}
delete = (url, params = {}) => {
this.setToken()
return this.http({
method: 'delete',
params: params,
url: url,
cancelToken: this.cancelToken
})
}
put = (url, data = {}) => {
this.setToken()
return this.http({
method: 'put',
data: data,
url: url,
cancelToken: this.cancelToken
})
}
}
let instance = new Http()
export default instance
小结
代码还有一些冗余的地方,这里只是提供一个思路~第一次在掘金写文章,自己还是一个小菜鸟,希望看过觉得有用的同仁能够鼓励鼓励,也祝福各位同仁生活愉快~~~~