axios
-
Vue發(fā)送網(wǎng)絡(luò)請求有非常多的方式炉旷,如何選擇系宜?
- 傳統(tǒng)的Ajsx是基于XMLHttpRequest(XHR)
- 配置和調(diào)用方式非撑嫱悖混亂
- jQuery-Ajax
- 為了一個網(wǎng)絡(luò)請求庸娱,引用jQuery,得不償失
- Vue1.x畦娄,有個Vue-resource
- Vue2.0已經(jīng)去掉又沾,不會再更新
- 傳統(tǒng)的Ajsx是基于XMLHttpRequest(XHR)
-
為什么axios
- 在瀏覽器中發(fā)送XMLHttpRequests請求
- 在node.js中發(fā)送http請求
- 支持Promise API
- 攔截請求和響應(yīng)
- 轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
-
axios請求方式
-
axios(config)
axios({ url: 'http://123.207.32.32:8000/home/multidata', method: 'get', //默認get請求 }).then((res)=>{ console.log(res) })
axios({ url: 'http://123.207.32.32:8000/home/multidata', method: 'get', //默認get請求 params: { //get請求的參數(shù),不用放在url后面用熙卡?拼接了 type: 'pop', page: 1 } }).then((res)=>{ console.log(res) })
axios.request(config)
axios.get(url[, config])
axios.delete(url[,config])
axios.head(url[,config])
axios.post(url[, data [,config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[,config]])
-
-
axios發(fā)送并發(fā)請求
axios.all([axios(), axios()]).then(results => {}) //可以將結(jié)果展開 axios.all([axios(), axios()]).then(axios.spread((res1, res2) => {}))
-
全局配置
//公共的配置 axios.defaults.baseUrl = "http://localhost:8080" axios.defaults.timeout = 5000 //超時時間5秒
-
常見的配置
- 請求地址:
url: '/user'
- 請求類型:
method: 'get'
- 根路徑:
baseUrl: 'http://localhost:8080'
- 請求前的數(shù)據(jù)處理:
transformRequest: [function(data){}]
- 請求后的數(shù)據(jù)處理:
transformResponse: [function(data){}]
- 自定義請求頭:
headers: {'x-Requested-With': 'XMLHttpRequest'}
- URL查詢對象:
params: {id: 12}
- 查詢對象序列化函數(shù):
paramsSerializer: fucntion(params){}
- request body:
data:{key: 'aa'}
- 超時設(shè)置:
timeout: 10000
- 跨域是否帶token:
withCredentials: false
- 自定義請求處理:
adapter: function(resolve, reject, config){}
- 身份驗證信息:
auth: {uname: '', pwd: '1243'}
- 響應(yīng)的數(shù)據(jù)格式:
responseType: 'json/blob/document/arraybuffer/text/stream'
- 請求地址:
-
axios實例
import axios from 'axios' const instance = axios.create({ bseURL: 'http://localhost:8080', timeout: 5000 }) //使用 instance({ url: '/user' }).then((res)=>{})
-
攔截器
const instance = axios.create({ baseURL: 'http://localhost:8080', timeout:5000 }) //攔截某個實例 //請求攔截 instance.interceptors.request.use(config=>{ console.log('請求成功攔截') return config }, err=>{ console.log('請求失敗攔截') return err }) //響應(yīng)攔截 instance.interceptors.response.use(response=>{ console.log('響應(yīng)成功攔截') return response.data },err=>{ console.log('響應(yīng)失敗攔截') return err }) //如果要全局攔截杖刷,直接用axios.interceptors就可以