Vue 中axios配置實例詳解
更新時間:2018年07月27日 15:08:13 作者:1461433958
本文通過實例代碼給大家介紹了Vue axios配置,非常不錯,代碼簡單易懂,具有一定的參考借鑒價值,需要的朋友可以參考下
1.GET 請求
//向具有指定ID的用戶發(fā)出請求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 也可以通過 params 對象傳遞參數 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2.POST請求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3執(zhí)行多個并發(fā)請求
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) { //兩個請求現已完成 }));
4.請求配置
這些是用于發(fā)出請求的可用配置選項。 只有url是必需的。 如果未指定方法,請求將默認為GET.
{ // `url`是將用于請求的服務器URL url: '/user', // `method`是發(fā)出請求時使用的請求方法 method: 'get', // 默認 // `baseURL`將被添加到`url`前面,除非`url`是絕對的。 // 可以方便地為 axios 的實例設置`baseURL`,以便將相對 URL 傳遞給該實例的方法。 baseURL: 'https://some-domain.com/api/', // `transformRequest`允許在請求數據發(fā)送到服務器之前對其進行更改 // 這只適用于請求方法'PUT','POST'和'PATCH' // 數組中的最后一個函數必須返回一個字符串,一個 ArrayBuffer或一個 Stream transformRequest: [function (data) { // 做任何你想要的數據轉換 return data; }], // `transformResponse`允許在 then / catch之前對響應數據進行更改 transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers`是要發(fā)送的自定義 headers headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params`是要與請求一起發(fā)送的URL參數 // 必須是純對象或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`是要作為請求主體發(fā)送的數據 // 僅適用于請求方法“PUT”,“POST”和“PATCH” // 當沒有設置`transformRequest`時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: 'Fred' }, // `timeout`指定請求超時之前的毫秒數。 // 如果請求的時間超過'timeout',請求將被中止。 timeout: 1000, // `withCredentials`指示是否跨站點訪問控制請求 // should be made using credentials withCredentials: false, // default // `adapter'允許自定義處理請求,這使得測試更容易。 // 返回一個promise并提供一個有效的響應(參見[response docs](#response-api)) adapter: function (config) { /* ... */ }, // `auth'表示應該使用 HTTP 基本認證,并提供憑據。 // 這將設置一個`Authorization'頭,覆蓋任何現有的`Authorization'自定義頭,使用`headers`設置。 auth: { username: 'janedoe', password: 's00pers3cret' }, // “responseType”表示服務器將響應的數據類型 // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress`允許處理上傳的進度事件 onUploadProgress: function (progressEvent) { // 使用本地 progress 事件做任何你想要做的 }, // `onDownloadProgress`允許處理下載的進度事件 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength`定義允許的http響應內容的最大大小 maxContentLength: 2000, // `validateStatus`定義是否解析或拒絕給定的promise // HTTP響應狀態(tài)碼。如果`validateStatus`返回`true`(或被設置為`null` promise將被解析;否則,promise將被 // 拒絕。 validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects`定義在node.js中要遵循的重定向的最大數量。 // 如果設置為0,則不會遵循重定向。 maxRedirects: 5, // 默認 // `httpAgent`和`httpsAgent`用于定義在node.js中分別執(zhí)行http和https請求時使用的自定義代理。 // 允許配置類似`keepAlive`的選項, // 默認情況下不啟用。 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy'定義代理服務器的主機名和端口 // `auth`表示HTTP Basic auth應該用于連接到代理,并提供credentials。 // 這將設置一個`Proxy-Authorization` header,覆蓋任何使用`headers`設置的現有的`Proxy-Authorization` 自定義 headers。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // “cancelToken”指定可用于取消請求的取消令牌 // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) }
5.全局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';
6.攔截器
你可以截取請求或響應在被 then 或者 catch 處理之前
//添加請求攔截器<==>請求發(fā)起前做的事 axios.interceptors.request.use(function(config){ //在發(fā)送請求之前做某事 return config; },function(error){ //請求錯誤時做些事 return Promise.reject(error); }); //添加響應攔截器<==>響應回來后做的事 axios.interceptors.response.use(function(response){ //對響應數據做些事 return response; },function(error){ //請求錯誤時做些事 return Promise.reject(error); });
如果你以后可能需要刪除攔截器。、
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
你可以將攔截器添加到axios的自定義實例
var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
總結
以上所述是小編給大家介紹的Vue 中axios配置實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
Ant Design Vue table組件如何自定義分頁器
這篇文章主要介紹了Ant Design Vue table組件如何自定義分頁器問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04淺談vue項目利用Hbuilder打包成APP流程,以及遇到的坑
這篇文章主要介紹了淺談vue項目利用Hbuilder打包成APP流程,以及遇到的坑,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09