1.在utils文件夹下新建 api.js 和 httpRequest.js 页面
httpRequest.js:
getApp().globalData.baseUrl = 'https://xxxxxx';
import api from "@/utils/api.js";
module.exports = {
httpRequest(url, method, param) {
var data = param.data;
var headerParam = {}
if (url.indexOf("/loginApp") != -1 ) { // 根据自身项目内容 再具体判断
headerParam = {}
} else {
headerParam = {
'Authorization': token != '' ? uni.getStorageSync('token') : '', //检查缓存中有没有token
'Content-Type': 'application/json;charset=utf-8'
}
}
let promise = new Promise(function(resolve, reject) {
uni.request({
url: getApp().globalData.baseUrl + url,
data: data,
method: method,
header: headerParam,
complete: (res) => { //请求完成
uni.hideLoading(); //隐藏加载
},
success: (res) => {
if (res.data.code == 200) {
resolve(res.data);
} else if (res.data.code === 401) {
reject(res.data.code);
} else {
uni.showToast({
title: res.data.msg,
icon: 'none'
});
reject(res.data.code);
}
},
fail: (err) => {
reject(err);
}
});
});
return promise;
}
}
api.js
// 在这里面定义所有接口
import { httpRequest } from './httpRequest';
// get请求--不带参数
function getApi(data) {
return httpRequest('/api', 'get', data)
}
// get请求--带参数
function getApi(data) {
return httpRequest('/api/' + data, 'get', data)
}
// post请求--不带参数
function getApi(data) {
return httpRequest('/api', 'post', data)
}
// put请求--不带参数
function getApi(data) {
return httpRequest('/api', 'put', data)
}
export default {
// 暴露接口 接口名
getApi,
......
}
页面调用
<script>
import api from "@/utils/api.js";
export default {
data() {
return {
list: []
}
},
methods: {
getIndexNav() {
// var param='' // 不传参
var param = {
id: ''
}
api.getApi(param).then(res => {
this.list = res.data;
})
},
}
}
</script>