一、說明
Axios是一個基於Promise(ES6中用於處理異步的)的HTTP庫(HTTP客戶端),用於瀏覽器和node.js中,API。
瀏覽器中創建XMLHttpRequests
從node.js中創建http請求
支持Promise API
攔截請求和響應
轉換請求數據和響應數據
取消請求
自動轉換JSON數據
客戶端支持防御XSRF
二、安裝
npm安裝:npm i axios;
使用cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
三、常用api說明
可使用 萬能地址 發送做測試。客戶端使用即在原來ajax代碼替換成axios。
1、get請求axios.get(url[, config])
// 為給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios對象調用get方法,.then()成功回調,.catch()失敗回調。
get方法也可以把url中的參數提出來單獨放到一個對象中。
2、post請求axios.post(url[, data[, config]])
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3、通用請求axios(config),通過向 axios 傳遞相關配置config對象來創建請求
axios({
methods: 'post',
url: 'http://jsonplaceholder.typicode.com/users',
data: {
name: 'qiurx'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
4、執行多個並發請求
function getUserAccount() {
return axios.get('/user/12345'); //請求1
}
function getUserPermissions() {
return axios.get('/user/12345/permissions'); //請求2
}
axios.all([getUserAccount(), getUserPermissions()]) //兩個請求放到數組中傳遞給all()
.then(axios.spread(function (acct, perms) { //多個請求都發送完畢,拿到返回的數據
// 兩個請求現在都執行完成
}));
axios中的all()方法,傳入一個數組,數組元素即為函數調用,函數中即為請求調用。
然后,then()回調方法中調用axios自己的spread()方法。
四、創建實例
可以使用自定義配置新建一個 axios 實例axios.create([config])
//create創建一個新的實例對象
var instance = axios.create({
url: 'http://jsonplaceholder.typicode.com/users',
imeout: 3000,
method: 'post'
});
//即可調用方法,和axios實例同
instance.get('http://jsonplaceholder.typicode.com/users').then(Response=>{
console.log(Response);
});
五、所有請求配置
只有 url 是必需的。
{
// `url` 是用於請求的服務器 URL
url: '/user',
// `method` 是創建請求時使用的方法
method: 'get', // 默認是 get
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
// 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務器發送前,修改請求數據
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據
transformResponse: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
// `headers` 是即將被發送的自定義請求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即將與請求一起發送的 URL 參數
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
// `paramsSerializer` 是一個負責 `params` 序列化的函數
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作為請求主體被發送的數據
// 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設置 `transformRequest` 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請求超時的毫秒數(0 表示無超時時間)
// 如果請求話費了超過 `timeout` 的時間,請求將被中斷
timeout: 1000,
// `withCredentials` 表示跨域請求時是否需要使用憑證
withCredentials: false, // 默認的
// `adapter` 允許自定義處理請求,以使測試更輕松
// 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
// 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默認的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的
// `onUploadProgress` 允許為上傳處理進度事件
onUploadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `onDownloadProgress` 允許為下載處理進度事件
onDownloadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `maxContentLength` 定義允許的響應內容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認的
},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目
// 如果設置為0,將不會 follow 任何重定向
maxRedirects: 5, // 默認的
// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// `keepAlive` 默認沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務器的主機名稱和端口
// `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據
// 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用於取消請求的 cancel token
// (查看后面的 Cancellation 這節了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
六、攔截器
在請求或響應被 then 或 catch 處理前攔截它們。
//請求攔截器
axios.interceptors.request.use(
function (config) {
// 在發送請求之前做些什么
return config;
},
function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
}
);
//響應攔截器
axios.interceptors.response.use(
function (config) {
// 對響應數據做點什么
return config;
},
function (error) {
// 對響應錯誤做點什么
return Promise.reject(error);
}
);
如果你以后可能需要刪除攔截器。
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可以將攔截器添加到axios的自定義實例。
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
七. 配置默認值
您可以指定將應用於每個請求的配置默認值。
(1) 全局axios默認值
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';
(2) 自定義實例默認值
//在創建實例時設置配置默認值
var instance = axios.create({
baseURL:'https://api.example.com'
});
//在實例創建后改變默認值
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
(3) 配置優先級順序
配置將與優先順序合並。 順序是lib / defaults.js中的庫默認值,然后是實例的defaults屬性,最后是請求的config參數。 后者將優先於前者。 這里有一個例子。
//使用庫提供的配置默認值創建實例
//此時,超時配置值為`0`,這是庫的默認值
var instance = axios.create();
//覆蓋庫的超時默認值
//現在所有請求將在超時前等待2.5秒
instance.defaults.timeout = 2500;
//覆蓋此請求的超時,因為它知道需要很長時間
instance.get('/ longRequest',{
timeout:5000
});
八、Vue項目中使用
安裝完后導入。
import axios from 'axios'
then()中的res返回包含頭、狀態、data數據等等,真正返回數據在此對象中的data。
使用有兩種方式。
1、axios 綁定到Vue的原型上
axios並沒有提供Vue.use()方法,需要綁定到Vue的原型上。
Vue.prototype.$axios = axios;
這樣可以在其他組件中通過this.$axios使用axios發送請求。
export default {
methods: {
getData() {
this.$axios
.get("http://jsonplaceholder.typicode.com/users")
.then(Response => {
console.log(Response);
});
}
}
};
注意可能出現的問題:this的指向問題。
$axios沒有定義或者get()沒有定義,是因為this不是指向vue實例。可以通過var _this = this或bind(this)把this傳遞進去。
2、單獨創建一個http.js文件,在其中配置axios,再使用export default進行導出,需要使用的位置直接使用此js模塊。