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

uni-request

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

特別之處

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

使用方式

uni-app框架中小程序

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

npm install uni-request --save

文件中引用

import uniRequest from 'uni-request';api

使用方法

請求方法的別名

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併發

相關文章
相關標籤/搜索