VUE中使用HTTP庫(kù)Axios方法詳解
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中
安裝Axios模塊
在Vue中使用,最好安裝兩個(gè)模塊axios 和vue-axios
$npm install axios vue-axios --save
然后引用并使用模塊
import Axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,Axios)
在組件中通過如下方式進(jìn)行使用
this.$http[method]()
Axios模塊特性
1、可以從瀏覽器中創(chuàng)建XHR對(duì)象
2、可以從nodeJS中創(chuàng)建HTTP請(qǐng)求
3、支持Promise API
4、可以攔截請(qǐng)求和響應(yīng)
5、可以轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
6、可以取消請(qǐng)求
7、可以自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
8、客戶端支持防御XSRF
Vue下使用使用Axios
下面是一些簡(jiǎn)單的請(qǐng)求實(shí)例
get請(qǐng)求
僅僅向后端請(qǐng)求數(shù)據(jù)
axios.get('index.php')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
通過URL向后端發(fā)送數(shù)據(jù),要使用params屬性,params屬性包含即將與請(qǐng)求一起發(fā)送的數(shù)據(jù)
運(yùn)行下列代碼后,請(qǐng)求URL變更為index.php?id=12345&text=%E5%B0%8F%E7%81%AB%E6%9F%B4
axios.get('index.php',{
params:{
id:12345,
text:'jb51'
}
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error)
})
當(dāng)然,也可以把數(shù)據(jù)直接寫到URL中
// 為給定 ID 的 user 創(chuàng)建請(qǐng)求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post請(qǐng)求
一般來說,post請(qǐng)求更多的是要提交數(shù)據(jù),params屬性里的數(shù)據(jù)會(huì)出現(xiàn)在請(qǐng)求主體中
[注意]如果是axios.create()方法中的params屬性,則其里面的數(shù)據(jù)會(huì)出現(xiàn)在URL參數(shù)中
但實(shí)際上,post方法不需要使用params屬性,它的第二個(gè)參數(shù)就是要發(fā)送的數(shù)據(jù)
axios.post('index.php',{
id:12345,
text:'jb51'
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error)
})
多并發(fā)請(qǐng)求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// acct為第一個(gè)請(qǐng)求的結(jié)果,perms為第二個(gè)請(qǐng)求的結(jié)果
}));
Axios中的API
axios()
可以通過向 axios 傳遞相關(guān)配置來創(chuàng)建請(qǐng)求
axios(config)
// 發(fā)送 POST 請(qǐng)求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[,config])
// 發(fā)送 GET 請(qǐng)求(默認(rèn)的方法)
axios('/user/12345');
別名
為方便起見,為所有支持的請(qǐng)求方法提供了別名
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]])
[注意]在使用別名方法時(shí), url、method、data 這些屬性都不必在配置中指定
并發(fā)
處理并發(fā)請(qǐng)求的助手函數(shù)
axios.all(iterable) axios.spread(callback)
實(shí)例方法
創(chuàng)建實(shí)例
可以使用自定義配置新建一個(gè) axios 實(shí)例
axios.create([config])
var instance = axios.create({
baseURL: 'http://www.dbjr.com.cn/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
實(shí)例方法
以下是可用的實(shí)例方法。指定的配置將與實(shí)例的配置合并
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]])
請(qǐng)求配置
這些是創(chuàng)建請(qǐng)求時(shí)可以用的配置選項(xiàng)。只有 url 是必需的。如果沒有指定 method,請(qǐng)求將默認(rèn)使用 get 方法
{
// `url` 是用于請(qǐng)求的服務(wù)器 URL
url: '/user',
// `method` 是創(chuàng)建請(qǐng)求時(shí)使用的方法
method: 'get', // 默認(rèn)是 get
// `baseURL` 將自動(dòng)加在 `url` 前面,除非 `url` 是一個(gè)絕對(duì) URL。它可以通過設(shè)置一個(gè) `baseURL` 便于為 axios 實(shí)例的方法傳遞相對(duì) URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請(qǐng)求數(shù)據(jù),只能用在 'PUT', 'POST' 和 'PATCH' 這幾個(gè)請(qǐng)求方法。后面數(shù)組中的函數(shù)必須返回一個(gè)字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)
transformResponse: [function (data) {
// 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// `headers` 是即將被發(fā)送的自定義請(qǐng)求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即將與請(qǐng)求一起發(fā)送的 URL 參數(shù),必須是一個(gè)無(wú)格式對(duì)象(plain object)或 URLSearchParams 對(duì)象
params: {
ID: 12345
},
// `paramsSerializer` 是一個(gè)負(fù)責(zé) `params` 序列化的函數(shù)(e.g. https://www.jb51.com/package/qs, http://api.jb51.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作為請(qǐng)求主體被發(fā)送的數(shù)據(jù),只適用于這些請(qǐng)求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設(shè)置 `transformRequest` 時(shí),必須是以下類型之一:string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParam,瀏覽器專屬:FormData, File, Blob,Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請(qǐng)求超時(shí)的毫秒數(shù)(0 表示無(wú)超時(shí)時(shí)間),如果請(qǐng)求花費(fèi)了超過 `timeout` 的時(shí)間,請(qǐng)求將被中斷
timeout: 1000,
// `withCredentials` 表示跨域請(qǐng)求時(shí)是否需要使用憑證
withCredentials: false, // 默認(rèn)的
// `adapter` 允許自定義處理請(qǐng)求,以使測(cè)試更輕松,返回一個(gè) promise 并應(yīng)用一個(gè)有效的響應(yīng) (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗(yàn)證,并提供憑據(jù),這將設(shè)置一個(gè) `Authorization` 頭,覆寫掉現(xiàn)有的任意使用 `headers` 設(shè)置的自定義 `Authorization`頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默認(rèn)的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)的
// `onUploadProgress` 允許為上傳處理進(jìn)度事件
onUploadProgress: function (progressEvent) {
// 對(duì)原生進(jìn)度事件的處理
},
// `onDownloadProgress` 允許為下載處理進(jìn)度事件
onDownloadProgress: function (progressEvent) {
// 對(duì)原生進(jìn)度事件的處理
},
// `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定義對(duì)于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認(rèn)的
},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目,如果設(shè)置為0,將不會(huì) follow 任何重定向
maxRedirects: 5, // 默認(rèn)的
// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時(shí)使用的自定義代理。`keepAlive` 默認(rèn)沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口,`auth` 表示 HTTP 基礎(chǔ)驗(yàn)證應(yīng)當(dāng)用于連接代理,并提供憑據(jù)。這將會(huì)設(shè)置一個(gè) `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設(shè)置的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用于取消請(qǐng)求的 cancel token
cancelToken: new CancelToken(function (cancel) {
})
}
下面是一個(gè)實(shí)例
let HTTP = axios.create({
baseURL: 'http://localhost/',
timeout:1000,
headers:{
'author':'xiaohuochai'
}
})
HTTP.post('index.php',{
id:12345,
text:'jb51'
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error)
})
結(jié)果如下

響應(yīng)結(jié)構(gòu)
某個(gè)請(qǐng)求的響應(yīng)包含以下信息
{
// `data` 由服務(wù)器提供的響應(yīng)
data: {},
// `status` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼
status: 200,
// `statusText` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息
statusText: 'OK',
// `headers` 服務(wù)器響應(yīng)的頭
headers: {},
// `config` 是為請(qǐng)求提供的配置信息
config: {}
}
使用 then 時(shí),將接收下面這樣的響應(yīng):
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
配置默認(rèn)值
可以指定將被用在各個(gè)請(qǐng)求的配置默認(rèn)值
全局的axios默認(rèn)值
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定義實(shí)例默認(rèn)值
// 創(chuàng)建實(shí)例時(shí)設(shè)置配置的默認(rèn)值
var instance = axios.create({
baseURL: 'https://www.jb51.com'
});
// 在實(shí)例已創(chuàng)建后修改默認(rèn)值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置優(yōu)先順序
配置會(huì)以一個(gè)優(yōu)先順序進(jìn)行合并。這個(gè)順序是:在 lib/defaults.js 找到的庫(kù)的默認(rèn)值,然后是實(shí)例的 defaults 屬性,最后是請(qǐng)求的 config 參數(shù)。后者將優(yōu)先于前者
// 使用由庫(kù)提供的配置的默認(rèn)值來創(chuàng)建實(shí)例
// 此時(shí)超時(shí)配置的默認(rèn)值是 `0`
var instance = axios.create();
// 覆寫庫(kù)的超時(shí)默認(rèn)值
// 現(xiàn)在,在超時(shí)前,所有請(qǐng)求都會(huì)等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費(fèi)很長(zhǎng)時(shí)間的請(qǐng)求覆寫超時(shí)設(shè)置
instance.get('/longRequest', {
timeout: 5000
});
攔截器
在請(qǐng)求或響應(yīng)被 then 或 catch 處理前攔截它們
// 添加請(qǐng)求攔截器
axios.interceptors.request.use(function (config) {
// 在發(fā)送請(qǐng)求之前做些什么
return config;
}, function (error) {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
});
// 添加響應(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);
});
如果想在稍后移除攔截器,可以這樣:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
可以為自定義 axios 實(shí)例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
錯(cuò)誤處理
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// 請(qǐng)求已發(fā)出,但服務(wù)器響應(yīng)的狀態(tài)碼不在 2xx 范圍內(nèi)
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
可以使用 validateStatus 配置選項(xiàng)定義一個(gè)自定義 HTTP 狀態(tài)碼的錯(cuò)誤范圍
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 狀態(tài)碼在大于或等于500時(shí)才會(huì) reject
}
})
取消
可以使用 CancelToken.source 工廠方法創(chuàng)建 cancel token,像這樣:
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 處理錯(cuò)誤
}
});
// 取消請(qǐng)求(message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.');
還可以通過傳遞一個(gè) executor 函數(shù)到 CancelToken 的構(gòu)造函數(shù)來創(chuàng)建 cancel token
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函數(shù)接收一個(gè) cancel 函數(shù)作為參數(shù)
cancel = c;
})
});
// 取消請(qǐng)求
cancel();
[注意] 可以使用同一個(gè) cancel token 取消多個(gè)請(qǐng)求
下面是一個(gè)實(shí)例
let CancelToken = axios.CancelToken;
let source = CancelToken.source();
let HTTP = axios.create({
baseURL: 'http://localhost/',
params:{
a:123
},
})
HTTP.post('index.php',{
id:12345,
text:'jb51'
},{
cancelToken: source.token,
}).then((response)=>{
commit('fnChangeList',{listData:response.data})
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.log('err');
}
});
source.cancel('Operation canceled by the user.');
最終在控制臺(tái)中打印出如下信息
Request canceled Operation canceled by the user.
更多關(guān)于VUE中使用HTTP庫(kù)Axios的文章大家可以點(diǎn)擊下面的相關(guān)鏈接
相關(guān)文章
vue3插槽:el-table表頭插入tooltip及更換表格背景色方式
這篇文章主要介紹了vue3插槽:el-table表頭插入tooltip及更換表格背景色方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
在 Vue 應(yīng)用中使用 Netlify 表單功能的方法詳解
Netlify 帶有內(nèi)置表單處理功能,可以用來存儲(chǔ)表單數(shù)據(jù),下載 csv 文件,同時(shí)可以在接收到新的提交時(shí)發(fā)送郵件通知或者通過配置 webhook 發(fā)送請(qǐng)求。這篇文章主要介紹了在 Vue 應(yīng)用中使用 Netlify 表單功能,需要的朋友可以參考下2019-06-06
vue項(xiàng)目中圖片選擇路徑位置static或assets的區(qū)別及說明
這篇文章主要介紹了vue項(xiàng)目中圖片選擇路徑位置static或assets的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
vue獲取v-for異步數(shù)據(jù)dom的解決問題
這篇文章主要介紹了vue獲取v-for異步數(shù)據(jù)dom的解決問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Vue請(qǐng)求JSON Server服務(wù)器數(shù)據(jù)的實(shí)現(xiàn)方法
這篇文章主要介紹了Vue請(qǐng)求JSON Server服務(wù)器數(shù)據(jù)的實(shí)現(xiàn)方法,需要的朋友可以參考下2018-11-11
element-ui和vue表單(對(duì)話框)驗(yàn)證提示語(yǔ)(殘留)清除操作
這篇文章主要介紹了element-ui和vue表單(對(duì)話框)驗(yàn)證提示語(yǔ)(殘留)清除操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09
VUE識(shí)別訪問設(shè)備是pc端還是移動(dòng)端的實(shí)現(xiàn)步驟
經(jīng)常在項(xiàng)目中會(huì)有支持pc與手機(jī)端需求,并且pc與手機(jī)端是兩個(gè)不一樣的頁(yè)面,這時(shí)就要求判斷設(shè)置,下面這篇文章主要給大家介紹了關(guān)于VUE識(shí)別訪問設(shè)備是pc端還是移動(dòng)端的相關(guān)資料,需要的朋友可以參考下2023-05-05

