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的重複點擊問題。vue
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以及一些其餘配置(其餘配置我就沒研究,到時候須要的時候在研究吧~)node
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
複製代碼
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。react
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對象ios
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
複製代碼
代碼還有一些冗餘的地方,這裏只是提供一個思路~第一次在掘金寫文章,本身仍是一個小菜鳥,但願看過以爲有用的同仁可以鼓勵鼓勵,也祝福各位同仁生活愉快~~~~git