引入的./baseSite.js
let baseSite = "" if(process.env.NODE_ENV === 'development'){ // 開發環境 baseSite = 'http://XXX' }else{ // 生產環境 baseSite = 'http://XXX' } export default baseSite
在api中封裝
import baseSite from './baseSite.js' import util from './util.js' // 同時發送異步代碼的次數,防止一次點擊中有多次請求,用於處理 // let ajaxTimes = 0; module.exports = { get: function(url, data, options = {}) { return this.request({ url, data, method: 'GET', ...options }); }, post: function(url, data, options = {}) { return this.request({ url, data, method: 'POST', ...options }); }, /** * @Function * @param {Object} options - 請求配置項 * @prop {String} options.url - 請求路徑 * @prop {Object} options.data - 請求參數 * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 響應的數據類型 * @prop {Object} [options.dataType = config.dataType] - 如果設為 json,會嘗試對返回的數據做一次 JSON.parse * @prop {Object} [options.header = config.header] - 請求header * @prop {Object} [options.method = config.method] - 請求方法 * @returns {Promise<unknown>} */ request: function(options = {}) { // ajaxTimes++; options.header = options.header || "application/x-www-form-urlencoded"; options.url = options.url || ''; options.data = options.data || {}; options.method = options.method || 'POST'; // 該方法里進行封裝服務端接口需要的檢驗數據,以及一些常規的流程封裝,如下(根據自己邏輯進行封裝) //options.data.token = 'xxxxx' let headerObj = { "content-type": options.header, } const token = uni.getStorageSync('token'); if (token) { headerObj.token = token; } // 加載頁面 動畫 // uni.showLoading({ // title: "加載中", // mask: true, // }); return new Promise((resolve, reject) => { uni.request({ url: baseSite + options.url, data: options.data, method: options.method, header: headerObj, success: function(result) { let errorcode = result.data.errno if (errorcode == 0) { // resolve調用后,即可傳遞到調用方使用then或者async+await同步方式進行處理邏輯 resolve(result.data.data) } else if (errorcode == 600) { util.showToast('請登錄帳號') util.goLogin() } else { util.showToast(result.data.errmsg) } }, fail: function(e) { console.log('error in...') // reject調用后,即可傳遞到調用方使用catch或者async+await同步方式進行處理邏輯 reject(e) }, // // 完成之后關閉加載效果 // complete: () => { // ajaxTimes--; // if (ajaxTimes === 0) { // // 關閉正在等待的圖標 // uni.hideLoading(); // } // } }) }) } }
需要在全局中配置 引入request.js文件
Vue.prototype.$request = request
在頁面中使用
async request() { let res = await this.$request.get('/index/index', {'請求參數'}).then(result => { console.log(result) return result })