基於Promise封裝uni-app的request方法,實現類似axio


uni-request

基於Promise封裝uni-app的request方法,h5和小程序均可使用

特別之處

  • 支持Promise API
  • 攔截請求和響應
  • 轉換請求和響應數據
  • 取消請求
  • 自動轉換為JSON數據
  • 超時請求
  • 告別callback
  • 支持默認請求前綴
  • 支持並發請求

使用方式

uni-app框架中

安裝(項目根目錄下運行)

npm install uni-request --save

文件中引用

import uniRequest from 'uni-request';

使用方法

請求方法的別名

uniRequest.request(config) uniRequest.get(url[, config]) uniRequest.delete(url[, config]) uniRequest.head(url[, config]) uniRequest.options(url[, config]) uniRequest.post(url[, data[, config]]) uniRequest.put(url[, data[, config]]) uniRequest.patch(url[, data[, config]]) 

全局配置

uniRequest.defaults.baseURL = 'https://yourapi.domain.com'; uniRequest.defaults.headers.common['Authorization'] = AUTH_TOKEN; uniRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 

發送get請求

// 向具有給定ID的用戶發出請求 uniRequest.get('/user?id=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 可選地,上面的請求也可以按照 uniRequest.get('/user', { data: { id: 'number' } }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // 想要使用 async/await? 將`async`關鍵字添加到外部函數/method async function getUser() { try { const response = await uniRequest.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } 

發送post請求

uniRequest.post('/user', { firstname : 'firstname', lastname : 'lastname' }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); 

以上就是基本用法,如果掌握了就可以使用了uni-request,下面是一份完整的代碼示例包含了在uni-app中使用uni-request和vuex的詳細用法,有問題可以評論區留言,會及時回復


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM