第一步新建 utils 文件夹内的 request.js
const baseUrl = '请求路径';
/* token 登录标识 */
let token = "";
/* 判断机型 因为后台会通过机型不一样,所使用的登录参数也不一样*/
let channel = ''
// #ifdef APP-PLUS
channel = 'app';
// #endif
// #ifdef MP-WEIXIN
channel = 'weixin';
// #endif
// #ifdef H5
channel = 'h5';
// #endif
const httpRequest = (url, data, method) => {
let userInfo = uni.getStorageSync('userInfo');
console.log(userInfo)
let obj ={
...data,
token:userInfo.token,
}
let httpDefaultOpts = {
url: baseUrl + url,
data: obj,
method: method,
header: {
'Content-type': 'application/x-www-form-urlencoded',
'content-type': 'application/json',
"Accept": 'application/json',
},
}
// resolve 是成功后的返回 在.then()里面 reject 是失败时候的返回 在 error 里面
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
console.log(res)
console.log(res[1].statusCode)
//后台返回错误信息 直接弹框
if (res[1].statusCode != 200) {
uni.showModal({
title: '提示',
showCancel: false,
content: res[1].data.message,
success: function(res) {
if (res.confirm) {}
}
});
}
//后台返回说 需要登录 直接跳登录页面
if (res[1].data.code < 0) {
uni.navigateTo({
url:"/pages/login/index"
})
}
resolve(res[1].data)
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
};
export default {
baseUrl,
httpRequest,
}
第二步新建 utils 文件夹内的 http.js
import request from '@/utils/request'
/* 首页类别对应的商品*/
function homeCate(data) {
let url = 'ys.Index/homeCate'
let method = "POST"
return request.httpRequest(url, data, method);
}
export default {
homeCate,
}
第三步挂载 http.js 前往main.js main是程序的口所有的加载都是通过这个js开始的
import Vue from 'vue'
import App from './App'
import uView from "uview-ui";
Vue.use(uView);
/*挂载的主要代码*/
import http from './utils/http.js'
Vue.prototype.$http = http
/*挂在代码完毕*/
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
第四步 调用
<script>
export default {
data() {
return {
}
},
onLoad() {
this.homeCateList()
},
methods: {
/* 首页类别对应的商品 */
homeCateList() {
/*这里传入你想传入的参数值*/
let data = {
}
this.$http.homeCate(data).then(res => {
console.log('请求成功', res)
}, error => {
console.log(error)
})
},
}
}
</script>