企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 此封装方法适用于uinapp ## 自己写的,后期可用加token验证 ## mian.js文件里 加上这个全局注册语句 ![](https://img.kancloud.cn/f4/dc/f4dcef13a21f00156aad615c93f7e2d4_1141x525.png) ``` Vue.prototype.$api = api //封装的网络接口 //添加全局变量 ``` ## 在根目录,也就是平等文件夹下建一个 api.js文件 ![](https://img.kancloud.cn/b3/99/b39984f36a54f72d4bb9fa49d7c61826_231x426.png) ``` const commoneUrl = "https://www3.zmkm.top"; //请求链接 //post请求封装 url参数为剩余链接, data为请求数据 function postRequest(url, data) { var promise = new Promise((resolve, reject) => { //用Promise方法进行封装 var postData = data; uni.request({ url: commoneUrl + url, header: { 'content-type': 'application/json', }, data: postData, method: 'POST', success: function(res) { if (res.statusCode == 200) { //成功以后赋值给 Promise 成功执行参数 resolve(res); resolve(res); } else if (res.statusCode == 500) { resolve(res); } }, fail: function(e) { //失败赋予失败方法 reject("网络错错误" + res); reject("网络错错误" + res); } }) }); 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', success: function(res) { resolve(res.data); }, error: function(e) { reject('网络出错' + res); } }); }); 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', success: function(res) { resolve(res.data); }, error: function(e) { reject('网络出错'); } }); }); return promise; }; module.exports = { post: postRequest, get: getRequest, put: putRequest, del: delRequest, ip: commoneUrl, }; ``` # 在组件里使用 ``` this.$api.post('/api/apix/txt/67').then(res => { console.log(res); }) ``` ![](https://img.kancloud.cn/21/ff/21ffd3e07ee7d865fee69db3246477ed_957x487.png)