1、创建一个对象,将该对象挂在Vue的原型下
新建@/common/request.js文件
const webUrl = 'http:/localhost:8082'export default{//封装uni.request():request(options){options.url = webUrl + options.urloptions.method = options.method || this.common.methodoptions.header = options.header || this.common.headerreturn new Promise((resolve,reject)=>{//书写异步操作的代码uni.request({...options,success:res=>{if(options.native){resolve(res) //调取接口后返回的原生数据}if(res.statusCode === 200){resolve(res.data) //异步操作执行成功}else{console.log('请求的接口没有找到');reject(res) //异步操作执行失败}}})})},get(url,data={},options={}){options.url=url;options.data=data;options.method='get';return this.request(options)},post(url,data={},options={}){options.url=url;options.data=data;options.method='post';return this.request(options)}}
const BASE_URL = 'http:/localhost:8082'export const myRequest = (options)=>{return new Promise((resolve,reject)=>{uni.request({url:BASE_URL+options.url,method:options.method || 'GET',data:options.data || {},success: (res) => {if(res.data.status !== 0){return uni.showToast({title:'获取数据失败'})}resolve(res)},fail: (err) => {uni.showToast({title:'请求借口失败'})reject(err)}})})}
const baseUrl = 'http:/localhost:8082'const request = (url = '', data = {}, type = 'GET', header = {}) => {return new Promise((resolve, reject) => {uni.request({method: type,url: baseUrl + url,data: data,header: header,dataType: 'json',}).then((response) => {setTimeout(function() {uni.hideLoading();}, 200);let [error, res] = response;resolve(res.data);}).catch(error => {let [err, res] = error;reject(err)})});}export default request
2、进入main.js文件
import request from '@/common/request.js';Vue.prototype.$Z = request;
例:在任意文件中书写下列代码可以调用。this.$Z.get();
3、在页面中调用
//封装uni.request():this.$Z.get('/api/getIndexCarousel.jsp',{},{native:false}).then(res=>{//异步操作成功console.log(res)}).catch(res=>{//异步操作失败console.log(res)}).finally(res=>{//异步操作完成});
async getPage(){const res = await this.$Z({url:'/api/getIndex'})this.page = res.data.message}
getPage(){this.$Z('/api/news', {// 传参参数名:参数值,如果没有,就不需要传}).then(res => {// 打印调用成功回调console.log(res)})}
