axios 配置及使用
在線CDN地址
https://unpkg.com/axios/dist/axios.min.js
安裝
npm i axios -S
導(dǎo)入
import axios from 'axios'
全局配置
方案一
創(chuàng)建實例的時候傳入配置對象
// 創(chuàng)建實例的時候傳入配置對象
const $https = axios.create({
baseURL: 'https://some-domain.com/api/', // 設(shè)置接口地址
timeout: 1000, //設(shè)置超時時間
headers: {'Content-Type': 'application/x-www-form-urlencoded'} //設(shè)置請求頭
});
先創(chuàng)建實例對象, 在進(jìn)行配置
// 先創(chuàng)建實例對象
const $https = axios.create();
// 再進(jìn)行配置
$https.defaults.baseURL='https://api.example.com' ;
// 設(shè)置超時時間
$https.defaults.timeout = 2500;
// 設(shè)置認(rèn)證請求頭
$https.defaults.headers.common['Authorization'] = AUTH_TOKEN;
需要使用實例對象$https發(fā)送請求
方案二
// 設(shè)置接口地址
axios.defaults.baseURL='http://www.api.com'
// 對提交給服務(wù)端的數(shù)據(jù)進(jìn)行預(yù)處理,將對象{}=>queryString查詢字符串的格式;
// 因為默認(rèn)提交的是json(Content-Type:application/json), 服務(wù)端無法對json直接處理
axios.defaults.transformRequest: [function (data, headers) {
// 對提交給服務(wù)端的數(shù)據(jù)進(jìn)行預(yù)處理
// data默認(rèn)為一個對象
if(typeof(data)=='object'){
let arr=[];
for(var key in data){
arr.push(key+'='+data[key]);
}
// 最終返回的數(shù)據(jù)格式:name=zs&age=30
return arr.join('&')
}
return data;
}];
// 設(shè)置公共請求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// 設(shè)置post請求頭
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
使用
發(fā)送get請求
axios.get('/user',{
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
發(fā)送post請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});