基於Promise封裝uni-app的request方法,實現類似axios形式的請求


https://my.oschina.net/u/2428630/blog/3004860

 

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


免責聲明!

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



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