引入的./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 })