1.首先创建项目根目录中创建utils/api.js
然后将下面代码复制到改文件中
// const commoneUrl = "http://192.168.20.112:8180"; //公共路径
const commoneUrl = "http://127.0.0.1"; //公共路径
const userId = uni.getStorageSync("userinfo_Data").id //用户id
//post请求封装
function postRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var postData = data;
uni.request({
url: commoneUrl + url,
data: postData,
method: 'POST',
// dataType:"jsonp",
// jsonp:"callbackparam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名
// jsonpCallback:"success_jsonpCallback",
header: {
'content-type': 'application/json;charset=UTF-8',
'token': uni.getStorageSync('token')
},
success: function(res) {
resolve(res.data);
},
error: function(e) {
reject('网络出错');
}
})
});
return promise;
}
//get请求封装
function getRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var postData = data;
uni.request({
url: commoneUrl + url,
data: postData,
method: "GET",
dataType: 'json',
header: {
'content-type': 'application/json',
'token': uni.getStorageSync('token')
},
success: function(res) {
resolve(res.data);
},
error: function(e) {
reject('网络出错');
}
});
});
return promise;
}
//put请求封装
function putRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var postData = data;
uni.request({
url: commoneUrl + url,
data: postData,
method: "PUT",
dataType: 'json',
header: {
'content-type': 'application/json',
'token': uni.getStorageSync('token')
},
success: function(res) {
resolve(res.data);
},
error: function(e) {
reject('网络出错');
}
});
});
return promise;
}
//del请求封装
function delRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var postData = data;
uni.request({
url: commoneUrl + url,
data: postData,
method: "DELETE",
dataType: 'json',
header: {
'content-type': 'application/json',
'token': uni.getStorageSync('token')
},
success: function(res) {
resolve(res.data);
},
error: function(e) {
reject('网络出错');
}
});
});
return promise;
}
// uni.addInterceptor('request', {
// invoke(args) {
// // request 触发前拼接 url
// // args.url = 'https://www.example.com/'+args.url
// uni.showLoading({
// title: "数据加载中...",
// duration: 500
// })
// // console.log('invoke', args);
// // console.log(args);
// },
// success(args) {
// // 请求成功后,修改code值为1
// uni.hideLoading()
// // args.data.code = 1
// },
// fail(err) {
// uni.$showMsg()
// uni.hideLoading()
// console.log('interceptor-fail', err)
// },
// complete(res) {
// // uni.hideLoading()
// // console.log('interceptor-complete', res)
// }
// })
module.exports = {
post: postRequest,
get: getRequest,
put: putRequest,
del: delRequest,
ip: commoneUrl,
userId: userId
};
2.在main.js中引入注册
import api from './utils/api.js'
Vue.prototype.api = api
3.在文件中就可以使用了
this.api.get('/data/getZHJSC').then(res => {
if (res.code != 1000) {
uni.redirectTo({
url: "/pages/login/login"
})
}
})