// 创建request.js文件
//通用uni-app网络请求
export default {
config: {
baseUrl: "", //默认的公共域名
header: {
'Content-Type':'application/json;charset=UTF-8', //默认get方式
},
data: {}, //上行参数
method: "GET", //默认GET方式
dataType: "json", /* 如设为json,会对返回的数据做一次 JSON.parse */
success() {}, //成功回调
fail() {}, //失败回调
complete() {} //完成回到
},
//封装两种请求方式,delete和put类似
get(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'GET'
return this.request(options)
},
post(url, data, options) {
if (!options) {
options = {}
}
options.url = url
options.data = data
options.method = 'POST'
return this.request(options)
},
//综合处理
request(options) {
if (!options) {
options = {}
}
options.baseUrl = options.baseUrl || this.config.baseUrl //设置全局url
options.dataType = options.dataType || this.config.dataType //设置数据类型
options.url = options.baseUrl + options.url //设置当前请求url
options.data = options.data || {} //设置参数
// #ifdef MP-ALIPAY
options.data.platform = 2
// #endif
options.method = options.method || this.config.method //设置请求方式
//header系列修改
if(options.method == "POST"){
this.config.header['Content-Type'] = 'application/x-www-form-urlencoded'
}else{
this.config.header['Content-Type'] = 'application/json;charset=UTF-8'
}
// 数据签名
var token = {'token': uni.getStorageSync('token') || ''}
options.header = Object.assign({}, options.header, this.config.header, token)
return new Promise((resolve, reject) => {
let _config = null
//定义成功失败的函数
options.success = res => {
console.log(res)
if (res.data.code == 200) {
resolve(res.data)
} else {
//获取失败后的逻辑
console.log('获取失败')
}
}
options.fail = err => {
// 请求接口错误
reject(res.data)
}
_config = Object.assign({}, this.config, options) //合并请求参数
//执行request请求
uni.request(_config);
});
}
}
在main.js中设置全局变量
import http from './utils/request' //全局request请求
// 定义请求方式
Vue.prototype.$http = http
在页面内调用
this.$http.get('user/indexCardV11', data).then(res => {
})