axios就是一個(gè)基于Promise的馋评,發(fā)送http請(qǐng)求的一個(gè)工具庫。
特點(diǎn)
- 支持Promise API
- 攔截請(qǐng)求和響應(yīng)刺啦。攔截請(qǐng)求留特,可以過濾請(qǐng)求參數(shù);攔截響應(yīng)玛瘸,可以處理響應(yīng)異常
- 取消請(qǐng)求蜕青。請(qǐng)求可以手動(dòng)取消
vue中使用axios
- 安裝axios模塊
npm install --save axios
- 在index.js文件中引入axios
import axios from 'axios'
new Vue({
// el: '#app',
// router,
axios // 加入axios
})
基本API
1. 執(zhí)行g(shù)et請(qǐng)求,有兩種方式
// 第一種方式 將參數(shù)直接寫在url中
axios.get('/getMainInfo?id=123')
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
// 第二種方式 將參數(shù)直接寫在params中
axios.get('/getMainInfo', {
params: {
id: 123
}
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
2. 執(zhí)行post請(qǐng)求糊渊,注意執(zhí)行post請(qǐng)求的入?yún)⒂液耍恍枰獙懺趐arams字段中,這個(gè)地方要注意與get請(qǐng)求的第二種方式進(jìn)行區(qū)別渺绒。
axios.post('/getMainInfo', {
id: 123
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
3. 通過向axios傳遞的相關(guān)配置來創(chuàng)建請(qǐng)求axios(config)
(1)下面是常用的配置字段:
- url:請(qǐng)求路徑蒙兰,string類型
- method:請(qǐng)求方法,string類型
- baseURL:baseURL會(huì)自動(dòng)加在url前面芒篷,除非url是一個(gè)絕對(duì)URL搜变,string類型
- transformRequest:允許在向服務(wù)器發(fā)送請(qǐng)求之前,修改請(qǐng)求數(shù)據(jù)针炉,只適用于post挠他,put,patch請(qǐng)求篡帕,數(shù)組類型殖侵,數(shù)組里面的最后一個(gè)函數(shù)必須返回一個(gè)字符串
[fucntion(data) {
// 對(duì)data進(jìn)行更改
return data
}]
- transformResponse:這里提前處理返回的數(shù)據(jù)
- headers:自定義請(qǐng)求頭
- params:即將于請(qǐng)求一起發(fā)送的url參數(shù)(一般只用于get請(qǐng)求)一般是對(duì)象類型
- data:作為請(qǐng)求主體被發(fā)送是數(shù)據(jù)(一般只用于post請(qǐng)求)一般是對(duì)象類型
- timeout:超時(shí)時(shí)間贸呢,超過時(shí)間,請(qǐng)求將被中斷
- withCredentials:表示跨域請(qǐng)求時(shí)是否需要使用憑證
- responseType:響應(yīng)數(shù)據(jù)的類型拢军,默認(rèn)是'json'楞陷,可以是'text', 'json','document','arraybuffer','blob','stream'
- maxContentLength:響應(yīng)數(shù)據(jù)的最大尺寸
- proxy:代理服務(wù)器主機(jī)名稱和端口
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
(2)下面是響應(yīng)的數(shù)據(jù)接口
{
data: // 服務(wù)器響應(yīng)數(shù)據(jù)
status: // http狀態(tài)碼
statusText: // 服務(wù)器響應(yīng)的http狀態(tài)信息
headers: // 響應(yīng)頭
config: // 請(qǐng)求配置數(shù)據(jù)
}
(3)舉例
// 發(fā)送 POST 請(qǐng)求
axios({
method: 'post',
url: '/getMainInfo',
data: {
id: 123
}
}).then(res => {
console.log(res.data)
console.log(res.status)
console.log(res.statusText)
console.log(res.headers)
console.log(res.config)
}).catch(err => {
console.log(err)
})
4. 配置默認(rèn)值default
axios.default.baseURL = ''
axios.default.headers.common['Authorization'] = AUTH_TOKEN
...等等默認(rèn)配置
5. 執(zhí)行多個(gè)并發(fā)
axios.all()
和Promise.all()執(zhí)行機(jī)制是一樣的,要么全部成功走then茉唉,要么就走catch
function getUserName() {
return axios.get('/getUseName?id=123')
}
function getUserAge() {
return axios.get('getUserAge?id=123')
}
axios.all([getUserName(), getUserAge()]) .then(
axios.spread(function(acct, perms) { // 處理并發(fā)請(qǐng)求的助手函數(shù)
console.log(acct, perms) // 全部請(qǐng)求成功
})).catch(err => {
console.log(err) // 只要任意一個(gè)請(qǐng)求出錯(cuò)
})
6. 攔截器
(1)在請(qǐng)求之前攔截請(qǐng)求
// 添加請(qǐng)求攔截器
axios.interceptors.request.use(function (config) {
// 在發(fā)送請(qǐng)求之前做些什么
return config;
}, function (error) {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
})
(2)在被then固蛾,catch處理前攔截響應(yīng)
// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
return response;
}, function (error) {
// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
return Promise.reject(error);
});
(3)可以為自定義 axios 實(shí)例添加攔截器
var instance = axios.create([config]);
instance.interceptors.request.use(function () {/*...*/});
7. 封裝axios
在開發(fā)中,總會(huì)有很多的http請(qǐng)求度陆,那我們就要封裝好一個(gè)axios艾凯,使用更方便一些
(1)封裝
// request.js文件
import axios from 'axios'
import qs from 'qs'
// 引入基礎(chǔ)參數(shù)文件 和 baseURL配置文件
import baseParams from './baseParams' // 基本參數(shù),比如一些登錄信息之類的參數(shù)
import { BASE_URL } from './config' // baseURL寫在config.js文件中
// 默認(rèn)的全局配置
axios.defaults.baseURL = BASE_URL
axios.defaults.timeout = 10000
// 請(qǐng)求發(fā)送之前攔截懂傀,進(jìn)行處理(根據(jù)業(yè)務(wù)需求進(jìn)行攔截處理)
axios.interceptors.request.use(success => {
return success
}, error => {
return reject(error)
})
// then,catch處理之前趾诗,進(jìn)行攔截處理(根據(jù)業(yè)務(wù)需求進(jìn)行攔截處理)
axios.interceptors.response.use(response => {
return response
}, error => {
return Promise.reject(error)
})
// 導(dǎo)出post請(qǐng)求
export function post (url, data, withBaseParams = false) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
url,
data: withBaseParams ? qs.stringify({...baseParams, data}) : qs.stringify(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then(res => successHandle(res, resolve)) // 將數(shù)據(jù)處理之后傳給頁面
.catch(err => errorHandle(err, reject))
})
}
// 導(dǎo)出get請(qǐng)求
export function get (url, params) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
params,
headers: {}
})
.then(res => successHandle(res, resolve))
.catch(err => errorHandle(err, reject))
})
}
// then處理執(zhí)行了successHandle
function successHandle(data, resolve) {
if (res.success && res.errorCode == '60000') {
resolve(res)
} else {
// 彈出toast報(bào)錯(cuò)
Toast({
message: res.msg,
duration: 2000
})
}
}
// catch處理執(zhí)行了errorHandle
function errorHandle(err, reject) {
reject(err)
}
(2)引入使用
// 引入使用
import {get, post} from 'request.js'
post('/getMainInfo', {id: 123}, true)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
寫在最后
感謝您的view