request / http.js
import store from '@/store/index.js';
const BASE_URL = '' //域名
export const myRequest = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: options.baseUrl +options.url || BASE_URL + options.url, // 接收请求的API
method: options.method || 'GET', // 收请求的方式,如果不传默认为GET
data: options.data || {}, // 接收请求的data,不传默认为空
header: options.header || {
auth: token,
"content-type": 'application/json'
},
success: (res) => { //数据获取成功
if (res.data.code == 2000) {
resolve(res) // 成功,将数据返回
} else { // 失败信息
uni.showToast({
title: res.data.message,
icon: 'error'
})
}
},
fail: (err) => { // 失败操作
uni.showToast({
title: "请求接口失败!"
})
reject(err)
}
})
})
}
main.js
挂在全局:
// 引入请求
import {
myRequest
} from './request/http.js'
//挂载到全局,让所有页面都能接收
Vue.prototype.$myRequest = myRequest //挂载到Vue的原型上
页面使用
页面使用:
async 方法名() { // 加载数据
const res = await this.$myRequest({ // 调用封装好的API请求函数
baseUrl:'域名',
url: 'api接口名', // 把接口传过去
method: 'GET',
})
this.shopData = res.data.data
}